Geo*_*ath 2 c operators operator-precedence
尽管C的输入相同,但F =(C * 9/5)+ 32和F =(9/5 * C)+ 32会产生两个不同的结果。我意识到运算符中存在某种优先级,但是我不确定。乘法在除法之前出现吗?
输入20时,华氏温度值在第一种情况下为68(正确),在第二种情况下为52。
#include<stdio.h>
int main()
{
float cel , fahr ;
printf("Enter the temperature(C): ");
scanf("%f",&cel);
fahr = (9/5 * celt is ) + 32;
printf("\nThe temperature in fahranheit is %f ",fahr);
}
Run Code Online (Sandbox Code Playgroud)
预期结果为68,但以上代码为52。如果我将位置切换为“ 9/5”和“ cel”,则结果正确。这是为什么 ?
乘法和除法在C中具有相同的优先级,并且具有从左到右的关联性。所以,
F = (C * 9/5 ) + 32 相当于 F = ((C * 9)/5) + 32F = (9/5 * C) + 32 相当于 F = ((9/5) * C) + 32这两个表达式在代数上是等效的,除了C定义的事实,int / int = int其余部分舍弃。因此,9/5不是您所期望的1.8,而是1。
要通过除以2来获得浮点结果int,您需要将至少一个操作数转换为float或double。因此,代替9/5,写:
9.0/5.0,9.0/5,9/5.0,或者1.8,它给你double,或9.0f/5.0f,9.0f/5,9/5.0f,或者1.8f,它给你float