C 聚合计算器中出现意外输出
我写了一个小代码,根据学生在所有5门科目中的分数计算学生的总分数和百分比,代码如下,但代码的输出出乎意料,当我在所有5门科目中输入学生的分数为100分时,则总分数和百分比为0.00C 聚合计算器中出现意外输出,c,C,我写了一个小代码,根据学生在所有5门科目中的分数计算学生的总分数和百分比,代码如下,但代码的输出出乎意料,当我在所有5门科目中输入学生的分数为100分时,则总分数和百分比为0.00 #include <stdio.h> #include <stdlib.h> int main() { /*Subjects of the student are s1, s2, s3, s4 and s5 am = aggregate marks & pm =
#include <stdio.h>
#include <stdlib.h>
int main()
{
/*Subjects of the student are s1, s2, s3, s4 and s5
am = aggregate marks & pm = percentage marks*/
int s1, s2, s3, s4, s5, am, pm;
printf("Enter the marks in order: ");
scanf("%f, %f, %f, %f, %f", &s1, &s2, &s3, &s4, &s5);
am = s1 + s2 + s3 + s4 + s5;
pm = am/5;
printf("Your aggregate marks are: %f", am);
printf("Your percentage marks are: %f", pm);
return 0;
}
#包括
#包括
int main()
{
/*学生的科目为s1、s2、s3、s4和s5
am=总分数,pm=百分比分数*/
int s1、s2、s3、s4、s5、am、pm;
printf(“按顺序输入标记:”);
scanf(“%f、%f、%f、%f、%f”、&s1、&s2、&s3、&s4、&s5);
am=s1+s2+s3+s4+s5;
pm=am/5;
printf(“您的合计分数为:%f”,am);
printf(“你的分数是:%f”,pm);
返回0;
}
它不能按预期工作,因为您要求scanf
从输入中读取5float
s,并将它们存储在int
s中。如果希望将输入视为整数,请使用%d
而不是%f
,如果希望变量为浮点数,请将变量声明更改为浮点。格式说明符和参数不匹配会导致未定义的行为。和你一样。我也建议你养成一个习惯,检查什么。即使这样做有效,也应该是平均值,而不是百分比。最后,整数算术永远不会产生浮点值。@TusharSharma:嗯,这是平均百分比。为什么%f用于float类型,而我为所有变量分配了float,所以使用%d对我来说没有任何意义,因为据我所知它用于int数据类型。您将变量声明为int
。这意味着编译器将它们视为整数,因此您无法告诉scanf
将它们视为float
s。