【发布时间】:2016-10-11 04:58:44
【问题描述】:
我正在开发一个程序,我必须在 if/else 中使用布尔运算符从用户那里获取温度值和度数符号,并打印出水所处的状态(冰、液体、蒸汽)。
输入输出示例:
Enter temperature, such as 31 F: 101c
Water is steam at 101c.
我的代码发布在下面。似乎它应该可以工作,但我认为我没有正确输入,因此没有输入循环。不知道如何修复它。
#include <stdio.h>
int main(void)
{
double temp;
char CorF;
printf("Please enter a temperature, such as 31 F:");
while (scanf_s("%lf %c", &temp, &CorF, 2) == 1)
{
if (temp <= 32 && CorF == 'F')
{
printf("Water is ice at %lf %c.\n", temp, CorF);
}
else if (temp >= 212 && CorF == 'F')
{
printf("Water is steam at %lf %c.\n", temp, CorF);
}
else if (temp > 32 && temp < 212 && CorF == 'F')
{
printf("Water is liquid at %lf %c.\n", temp, CorF);
}
else if (temp <= 0 && CorF == 'C')
{
printf("Water is ice at %lf %c.\n", temp, CorF);
}
else if (temp >= 100 && CorF == 'C')
{
printf("Water is steam at %lf %c.\n", temp, CorF);
}
else if (temp < 0 && temp > 100 && CorF == 'C')
{
printf("Water is liquid at %lf %c", temp, CorF);
}
else
{
// blank line!
}
}
return 0;
}
【问题讨论】:
-
scanf返回成功转换的次数,因此 good 在您的情况下返回值为 2。此外,如果用户 确实 输入101c,因为'c'和'C'不一样,所以条件都不满足 -
scanf_s("%lf %c", &temp, &CorF, 2) == 1-->scanf_s("%lf %c", &temp, &CorF, 1) == 2 -
temp < 0 && temp > 100-->temp > 0 && temp < 100 -
当您确定“我的循环没有被输入”时,与其花时间在这里发布问题,不如问问自己“为什么会这样?”...答案,如果您不确定,是实验。问“我想知道
sscanf_s正在返回什么值”。使用调试器,或更改代码以存储和显示结果。这种探索和好奇的基本技能将使您免于询问 99% 的问题,否则您可能会在本网站上提出这些问题。
标签: c if-statement while-loop temperature