gpt4 book ai didi

C计算器程序输出0

转载 作者:太空宇宙 更新时间:2023-11-04 06:31:58 25 4
gpt4 key购买 nike

尝试编写一个简单的程序,使用常量变量计算给定天数内的体重减轻量。一切看起来都对,但它输出 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

}

最佳答案

你有双天;,所以你需要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

关于C计算器程序输出0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19636892/

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