我正在编写一个计算平均成绩的C程序,并告诉您是否通过。用户可以根据需要选择尽可能多的尝试,并且将给出所有尝试的最终平均值。这是我的代码:
#include <stdio.h>
int main(void)
{
int num1;
double num2, num3, average, average_1;
printf("Enter number of attempts: ");
scanf("%d", &num1);
while (num1 > 0) {
printf("Enter your mark for subject one: ");
scanf("%lf", &num2);
printf("Enter your mark for subject two: ");
scanf("%lf", &num3);
if (num2 < 50 || num3 < 50) {
printf("You have failed \n");
} else {
printf("You have passed \n");
}
num1--;
}
average = num1 * num2 * num3;
average_1 = average / 100;
printf("Average for all %d attempts is %.2f \n", num1, average_1);
}
这段代码的问题在于最后的输出,即最后的printf行,给出了0次尝试,0次为平均值。这是确切的输出:
Enter number of attempts: 2 Enter your mark for subject one: 49 Enter your mark for subject two: 96 You have failed Enter your mark for subject one: 22 Enter your mark for subject two: 100 You have failed Average for all 0 attempts is 0.00
答案 0 :(得分:0)
您的循环将迭代,直到num1
大于0
。当它递减并成为0
程序时,num1
具有值0
。因此,在这些表达式num1
中0
-
average = num1*num2*num3; // 0*num2*num3 therefore , 0
average_1 = average / 100; // as average is 0 , thus result is 0
计算average_1
的公式也是错误的。它应该是 -
average_1=average/3; // you calculate average of 3 numbers
要获得正确的输出,请创建一个临时变量 -
int i=num1;
while(i>0){
// your code
i--;
}
这样num1
保持不变。
答案 1 :(得分:0)
您已将平均计算部分放在错误的位置。一旦您离开while
循环,num1
将具有值0
,因此所有相关计算都将返回0.
答案 2 :(得分:0)
您正在减少num1
,直到它变为0
while (num1 > 0) {
// other code
num1--;
}
然后自然
average = num1*num2*num3;
成为
average = 0*num2*num3;
那是0
答案 3 :(得分:0)
首先,因为你将num1减去一,直到0。
你应该使用for循环:
for(int counter = num1; num1 > 0; num--)
{ Your code here }
答案 4 :(得分:0)
您正在改变变量num1。因此,当您完成循环时,您将获得num1 = 0。
我建议你做一个'for'而不是'while'。像这样:
#include <stdio.h>
int main(void) {
int num1, i;
double num2,num3,average,average_1;
printf("Enter number of attempts: ");
scanf("%d", &num1);
for(i = num1; i > 0; i--) {
printf("Enter your mark for subject one: ");
scanf("%lf", &num2);
printf("Enter your mark for subject two: ");
scanf("%lf", &num3);
if (num2 < 50 || num3 < 50) {
printf("You have failed \n");
}
else {
printf("You have passed \n");
}
}
average = num1*num2*num3;
average_1 = average / 100;
printf("Average for all %d attempts is %.2f \n", num1, average_1);
}
答案 5 :(得分:0)
在while循环之后,你的num1将为0。