尝试制作一个简单的程序,使用常量变量计算给定天数内的重量损失量。一切看起来都对我而且输出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
}
答案 0 :(得分: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