-1

好的,所以我必须创建一个天气程序,当我尝试运行代码时,我没有收到任何错误,但它只会打印“输入起始温度”和“输入结束温度”。但是它不会让我为它输入数据。我有什么需要改变的吗?我知道我还没有完成代码,但我只是想在继续其余代码之前测试输入。谢谢您的帮助!

#include <stdio.h>
int main(int argc, char **argv)
{
    float celcius, fahrenheit, kelvin, ending, interval;
    int c, f, k, temp;

    printf("which temperature is being input? (C,F,K) ");
    scanf("%d", &temp);
    if (temp == c)
    {
        printf("enter a starting temperature");
        scanf("%f", &celcius);
        printf("enter an ending temperature");
        scanf("%f", &ending);
        fahrenheit = celcius * 9 / 5 + 32;
        kelvin = celcius + 273.15;
    }
    if (temp == f)
    {
        printf("enter a starting temperature");
        scanf("%f", &fahrenheit);
        celcius = fahrenheit - 32 * 5 / 9;
        kelvin = fahrenheit - 32 * 5 / 9 + 273.15;
        printf("enter an ending temperature");
        scanf("%f", &ending);
        if (temp == k)
        {
        }
        printf("enter a starting temperature");
        scanf("%f", &kelvin);
        fahrenheit = kelvin - 273 * 1.8 + 32;
        celcius = kelvin - 273.15;
        printf("enter an ending temperature");
        scanf("%f", &ending);
    }
}
4

4 回答 4

3

这个:

if (temp == c)

将新读取的值temp与未初始化变量中的未定义值进行比较c。这是未定义的行为。

你可能是说

if (temp == 'c')

与角色进行比较,但您还需要:

char temp;
if (scanf("%c", &temp) == 1)
{
  if (temp == 'c')
  {
    /* more code here */
  }
}

请注意,检查返回值scanf()有助于使程序更加健壮,并避免进一步使用未初始化的值(如果scanf()无法读取某些内容,则不应读取目标变量,因为它不会被写入)。

于 2013-10-08T16:51:20.660 回答
0

您的变量 temp 被声明为整数。实际上,scanf() 想要读取一个整数 (%d),但得到一个字符。因此,您将 temp 读取为 char。此外,您可以使用

9.0/5.0

代替

9/5

此外,使用 switch 语句会增加可读性。

于 2013-10-08T17:02:21.117 回答
0
if (temp == c)

您正在将 temp 与未初始化的 c 值进行比较

同样的

if (temp == f)

那么一切都会正常工作,为了使其更加用户友好,请在 printf 中添加一个 '\n'

像这样,

printf("enter a starting temperature \n");
于 2013-10-08T16:56:32.107 回答
0

这里:

printf("which temperature is being input? (C,F,K) ");
scanf("%d", &temp);

您要求输入一个字符,但随后您尝试扫描一个int. 这会打断你所有的scanf()电话。

于 2013-10-08T16:59:29.627 回答