C程序没有给出正确的输出

时间:2015-10-03 22:40:45

标签: c

我有以下代码要求用户输入正数天,然后要求用户输入当天的最高和最低温度,但是在我运行时编译代码后,我要求程序它要求最高温度的天数然后它只是结束程序而不要求最低温度和条件。这是代码。

#include <stdio.h>
int main(void) {

    int days,condt;
    double high,low,aver;

    printf("Weather Analyzer \n");
    printf("================ \n");

    printf("Please enter a positive number of days:");
    scanf("%d", &days);



    if (days <= 0) {

            while (days <= 0) {
                    printf("Please enter a positive number of days:");
                    scanf("%d", &days);
            }
    }



    printf("Enter today's high:");
    scanf("%.2f", &high);

    printf("Enter today's low:");
    scanf("%.2f", &low);

    printf("Enter today's condition: (s: sunny, c: cloudy, p: precipitation");
    scanf("%d", &condt);

    aver = high + low / 2.0;

    printf("Today's average temperature is: %.2f", aver);

}

这是确切的输出:

Weather Analyzer
================
Please enter a positive number of days:3
Enter today's high:1
Enter today's low:Enter today's condition: (s: sunny, c: cloudy, p: precipitationToday's average temperature is: -0.00admin@machine:~/cprogram/weather>

2 个答案:

答案 0 :(得分:4)

此处highlowdouble。将"%.2f"中的scanf更改为"%lf"。要获得正确的功能,请将condt声明为char。然后你就可以得到&#39;或者&#39; c&#39;在" %c"中使用scanf的值。

如果您选择将condt用作int,请使用1或2指定以下条件:

 printf("Enter today's condition: (1: sunny, 2: cloudy, 3: precipitation"); 

然后检查条件并进行计算。

答案 1 :(得分:0)

试试这个;

#include <stdio.h>
int main(void) {

    int days;
    char condt;
    double high,low,aver;

    printf("Weather Analyzer \n");
    printf("================ \n");

    printf("Please enter a positive number of days:");
    scanf("%d", &days);



    if (days <= 0) {

            while (days <= 0) {
                    printf("Please enter a positive number of days:");
                    scanf("%d", &days);
            }
    }



    printf("Enter today's high:");
    scanf("%lff", &high);

    printf("Enter today's low:");
    scanf("%lff", &low);

    printf("Enter today's condition: (s: sunny, c: cloudy, p: precipitation");
    scanf(" %c", &condt);

    aver = high + low / 2.0;

    printf("Today's average temperature is: %llf \n", aver);
    system("pause");
}