我正在学习 C 编程入门教程。 它告诉我编写一个简单的程序,将摄氏度转换为华氏度。
我按照视频中显示的方式编写了代码,但它只打印了第一行,然后就卡住了。
我不明白我的程序出了什么问题:
#include <stdio.h>
//program to convert Celsius to Fahrenheit
int main()
{
int c;
int f;
printf("Enter the temperature in Celsius:");
scanf("%d\n", &c);
f=9*c/5 + 32;
printf("The temperature in Fahrenheit is: %d\n",f);
return 0;
}
我最近开始使用 Ubuntu 并使用 Code Block 构建程序,并使用 gcc 作为编译器。
请帮忙 谢谢;
最佳答案
问题出在这行代码:
scanf("%d\n", &c);
转义序列 '\n' 在这种情况下的行为并不像您认为的那样:它没有告诉 scanf() 期望输入 x\n 形式的 x 数字,其中 '\n' 是换行但实际上被解释为必须完全匹配的模式,因为 scanf() 不会扩展转义序列。
Other characters in the template string that are not part of conversion specifications must match characters in the input stream exactly; if this is not the case, a matching failure occurs.
因此,如果您输入 10\n(其中\n 是实际字符而不是换行符),您的程序就可以运行。
由于这显然不是您要查找的行为,因此您可以通过从用于调用 scanf() 的模板字符串中删除\n 来解决问题。
在任何情况下,默认情况下 scanf() 都会忽略空格(例如 '\n')除非您使用 %c 或 %[ 作为转换说明符,因此无需尝试处理它。
顺便说一下,这一行有一个错误
f=9*c/5 + 32;
正确的换算公式是
f=(9/5) * c + 32;
在进行计算机算术运算时,运算顺序会影响最终结果。 (无论如何,在这种情况下,最好使用 float 来限制精度损失)
关于c - 程序卡在程序的第一个打印行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29182601/