Tyl*_*ler -3 c ruby python r operator-precedence
有人知道为什么负数需要括号的方式可以像人们在几种编程语言中所期望的那样,而不是在C语言中(或者在其他语言中)?
这是R中的一个例子:
> -5^2
[1] -25
> # now let's use parentheses
> (-5)^2
[1] 25
Run Code Online (Sandbox Code Playgroud)
Python中也发生了同样的事情:
>>> -5**2
-25
>>> (-5)**2
25
Run Code Online (Sandbox Code Playgroud)
只是为了好玩,我们也可以在Ruby中尝试这个(使用http://repl.it/作为解释器):
> 5**2
=> 25
> -5**2
=> -25
> (-5)**2
=> 25
Run Code Online (Sandbox Code Playgroud)
但是,如果我们在C中实现这个短程序,那么负数不需要括号正确平方:
#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;
}
Run Code Online (Sandbox Code Playgroud)
这是C程序的输出:
Enter the number you want squared: 5
Squared number: 25
Run Code Online (Sandbox Code Playgroud)
接下来,我将使用负数:
Enter the number you want squared: -5
Squared number: 25
Run Code Online (Sandbox Code Playgroud)
如果有人知道这背后的故事,我很想知道.
在第一个实施例(Python和Ruby,R)指数运算符具有较高的优先级,我们可以看到,是用于Python从壳体的Python运算符优先级,红宝石从红宝石运算符优先级从和R 运算符语法和优先级.所以指数运算符将在一元减去之前应用.
值得注意的是,正如Vincent Zoonekynd所指出的,Excel在这种情况下的行为实际上与OP的预期相同,因此根据您的背景,问题可能实际上并不像许多评论所说的那样明显.
这里的误解似乎是你希望它-成为数字的一部分,而不是.在-实际上是被应用到数字就像幂的运算符.
在C中,您输入的是负数,因此没有运算符优先权来处理.这里参考的是C 运算符优先级表.
所以你在这里比较两个不同的东西,如果你做了一些事情,让我们说Python你会看到类似的结果:
>>> x = -5
>>> x**2
25
Run Code Online (Sandbox Code Playgroud)