0

尝试制作一个简单的程序,使用一个常数变量计算给定天数内的体重减轻量。一切对我来说都是正确的,但它输出 0 作为答案?任何帮助将非常感激!

#include <stdio.h>
#include <stdlib.h>

int main(){

double days; //declaring variables that will be enetred by user
const float weightLoss = 0.04; //declaring constant to be used in calculation
float overallLoss; //float that is used to display overall result

printf("Please enter how many days you are going to fast for: \n"); 
scanf("%f", &days); //scans keyboard for input and assigns to designated variable
printf("You entered: %f\n", days); 

overallLoss = days * weightLoss; 

printf("You will lose %.2f stone", overallLoss); //print of the final result

}
4

1 回答 1

4

你有double days;,所以你需要scanf("%lf", &days)。或者您可以使用float days;当前格式。

有了printf(),你就不需要l; ,scanf()这是至关重要的。

不要忘记用换行符结束输出;你的最后一个printf()缺少一个。此外,一些编译器(例如 GCC 和 clang)会针对格式字符串和所提供的类型之间的这种不匹配提供警告。确保您使用适当的选项(gcc -Wall例如)来诊断它们。

工作代码

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    double days;
    const float weightLoss = 0.04; // Dimension: stone per day
    float overallLoss;

    printf("Please enter how many days you are going to fast for: ");
    if (scanf("%lf", &days) != 1)
    {
        fprintf(stderr, "Oops!\n");
        exit(1);
    }
    printf("You entered: %13.6f\n", days);

    overallLoss = days * weightLoss;

    printf("You will lose %.2f stone\n", overallLoss);

    return 0;
}

样本输出

第一次运行:

Please enter how many days you are going to fast for: 12
You entered:     12.000000
You will lose 0.48 stone

第二次运行:

Please enter how many days you are going to fast for: a fortnight
Oops!

如果您还没有了解这些内容,则可以放弃if测试,只要您准确输入输入即可;它必须是一个可识别的数字。

替代代码

使用float days而不是double days.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    float days;
    const float weightLoss = 0.04; // Dimension: stone per day
    float overallLoss;

    printf("Please enter how many days you are going to fast for: ");
    if (scanf("%f", &days) != 1)
    {
        fprintf(stderr, "Oops!\n");
        exit(1);
    }
    printf("You entered: %13.6f\n", days);

    overallLoss = days * weightLoss;

    printf("You will lose %.2f stone\n", overallLoss);

    return 0;
}

样本输出

Please enter how many days you are going to fast for: 10
You entered:     10.000000
You will lose 0.40 stone
于 2013-10-28T14:07:25.287 回答