Question

Does someone know the reason why negative numbers need parentheses to be squared the way one might expect in several programming languages but not in C (or perhaps others)?

Here's an example in R:

> -5^2
[1] -25
> # now let's use parentheses
> (-5)^2
[1] 25  

The same thing happens in Python:

>>> -5**2
-25
>>> (-5)**2
25

Just for fun, let's also try this in Ruby (used http://repl.it/ as the interpreter):

 > 5**2
=> 25
 > -5**2
=> -25
 > (-5)**2
=> 25

However, if we implement this short program in C, then negative numbers do not require parentheses to be squared correctly:

#include <stdio.h>

int main(void){
  int number, product;
  printf("\nEnter the number you want squared: ");
  scanf("%d", &number);
  product = number * number;
  printf("Squared number: %d \n", product);
  return 0;
}

Here's the output from the C program:

Enter the number you want squared: 5
Squared number: 25 

Next, I'll use a negative number:

Enter the number you want squared: -5
Squared number: 25 

If someone knows the story behind this, I'd love to know.

Was it helpful?

Solution

In the first examples(Python, Ruby, R) the exponential operator has higher precedence, we can see that is the case for Python from Python Operator Precedence, Ruby from Ruby Operator Precedence and R from Operator Syntax and Precedence. So the exponential operator will be applied before the unary minus will.

It is worth it to note that as Vincent Zoonekynd points out Excel actually behaves the way the OP expects in this case and so depending on your background the problem may actually not be as obvious as a lot of the comments purport.

The misunderstanding here appears to be that you expect the - to be part of the number, which it is not. The - is actually an operator which is applied to the number just like exponentiation.

In C you are entering a negative number and therefore there is no operator precedence to deal with. For reference here is C operator precedence table.

So you are comparing two different things here, if you did something in let's say Python you would see a similar result:

>>> x = -5
>>> x**2
25

OTHER TIPS

Suppose you write enter image description here on your math homework. This means enter image description here, not enter image description here. It's the same in R, Python, and Ruby. When you write -5**2, that means -(5**2), not (-5)**2. The exponentiation operator has a higher precedence than the negation.

On the other hand, when you do

product = number * number;

with a negative number, this multiplies the negative number by itself. The negation occurs before the squaring instead of afterward. If you did the same thing in any of the other languages you tried, you would get the same result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top