我正在开发一个程序,我必须在if / else中使用布尔运算符来获取用户的温度值和度数符号,并打印出水所处的状态(冰,液体,蒸汽)。 / p>
示例输入&输出:
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;
}
答案 0 :(得分:0)
您的代码中存在很多错误。 虽然是循环,但它用于循环。当您使用scanf_s进行检查时,它将在循环中每次进入时检查值。 而不是使用while应该使用if语句。
#include<stdio.h>
int main(void)
{
double temp;
char CorF;
printf("Please enter a temperature, such as 31 F:");
int i=scanf("%lf %c", &temp, &CorF);
if(i==2)
{
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:成功时,该函数返回成功读取的项目数。如果发生匹配故障,此计数可以匹配预期的读数或更少,甚至为零。如果在成功读取任何数据之前输入失败,则返回EOF。