你有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