gpt4 book ai didi

c - 水的状态(温度程序)- C 编程

转载 作者:行者123 更新时间:2023-11-30 19:37:21 26 4
gpt4 key购买 nike

我正在开发一个程序,我必须在 if/else 中使用 bool 运算符从用户处获取温度值和度数符号,并打印出水所处的状态(冰、液体、 Steam )。

输入和输出示例:

   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;

}

最佳答案

你的代码中有很多错误。while是一个循环,用于循环。当您使用 scanf_s 检查它时,它会在每次进入循环时检查该值。您应该使用 if 语句,而不是使用 while。

#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。

关于c - 水的状态(温度程序)- C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39970742/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com