c - C中公式的随机输出

标签 c

当我这样运行我的公式时,我得到随机答案:

    int main (void)
{
    int F = 120;


    printf("%i Farenheit in Celsius is %i\n", F, (F - 32) / 1.8);

    return 0;
}

但是当我将代码更改为:

    int main (void)
{
    int F = 120, C;

    C = (F-32)/1.8;
    printf("%i Farenheit in Celsius is %i\n", F, C);

    return 0;
}

它是一致的并给出了正确的答案。 为什么第一个版本不能正常工作?

最佳答案

这是因为在您的第一个版本中,您在将结果减到 F - ... 中的 F 之前执行了 32/1.8:

printf("%i Farenheit in Celsius is %i\n", F, F - 32 / 1.8); //32/1.8 gets operated first

因此,您在第一个版本中始终得到 F - 17.777777778

/ 部分的优先级高于 -。检查this出去。

您遇到的另一个问题是 Cint 类型。因此用 %i 打印它适合第二个版本:

int F = 120, C;

C = (F-32)/1.8; //C is int, so the result is rounded here
printf("%i Farenheit in Celsius is %i\n", F, C); //printing int with %i is OK

但请注意,在您的第一个版本中,F - 32/1.8 的结果将类型提升为 float (如float/double) 但您正在尝试使用 %i 格式打印 float 。

printf("%i Farenheit in Celsius is %i\n", F, F - 32 / 1.8);
//The F - 32 / 1.8 expression here is 
//int - int / double -> resulting in double type
//but you print double type with %i -> does not match

解决方案:给出括号,并将打印格式更改为%f以打印 float :

printf("%i Farenheit in Celsius is %f\n", F, (F - 32) / 1.8); //note the %f

关于c - C中公式的随机输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36193488/

相关文章:

C 'float' 生成随机答案

c - 将struct中的指针设置为C中的数组

c - 读取除最后一个之外的所有缓冲区(在 C 中)

sql嵌入c程序对几个表进行排名

c - 如何在 GTK 中将图像堆叠在绘图区域上方

c - 下标运算符的评估顺序

c# - 使用java或其他编程语言将小图标添加到任何文件/文件夹作为Windows中的图标

python - 在 cython 中指定大于 long double 的数字

c++ - 头文件之谜

C语言比较链表中的chararrays