我试图通过在while循环中使用if语句来阻止用户在这个简单的C程序中输入错误的值。但问题是,每当用户输入错误的值时,它就会存储在变量中,然后使用相同的值进行进一步的计算。 这是实际的程序:
#include <stdio.h>
#include <stdlib.h>
/*Program to calculate the marks obtained scored by the class in a quiz*/
int main()
{
float marks, average, total = 0.0;
int noStudents;
printf("Enter the total number of students: ");
scanf("%d", &noStudents);
int a=1;
while(a<=noStudents)
{
printf("Enter marks obtained out of 20: ");
scanf("%f", &marks);
if(marks<0 || marks >20)
{
printf("You have entered wrong marks\nEnter again: ");
scanf("%d", &marks);
}
total = total+marks;
a++;
}
average = total/(float)noStudents;
printf("Average marks obtained by the class are: %f", average);
return 0;
}
答案 0 :(得分:2)
第一个问题是代码中的不一致。在条件声明正文中,你写了
scanf("%d", &marks);
使用%d
的不匹配参数类型。这会调用undefined behavior。您应该像以前一样使用%f
。
那就是说,
average = total/(float)noStudents;
中,您不需要演员表。其中一个操作数total
已经是float
类型,因此即使没有显式转换,另一个操作数也会自动升级并进行浮点除法。答案 1 :(得分:0)
略微调整了您的代码。希望能帮助到你。正如其中一条评论中已经提到的那样,不要期望用户在超出范围的情况下给出正确的值。您应继续要求用户输入范围,除非他输入正确的值。
#include<stdio.h>
#include<stdlib.h>
int main()
{
float marks, average, total = 0.0;
int noStudents;
printf("Enter the total number of students: ");
scanf("%d", &noStudents);
int a=1;
while(a<=noStudents)
{
printf("Enter marks obtained out of 20: ");
scanf("%f", &marks);
if(marks<0 || marks >20)
{
printf("You have entered wrong marks.Enter again:\n ");
continue;
}
total = total+marks;
a++;
}
average = total/noStudents;
printf("Average marks obtained by the class are: %f", average);
return 0;
}