gpt4 book ai didi

C 程序输出不正确?

转载 作者:行者123 更新时间:2023-11-30 17:09:50 25 4
gpt4 key购买 nike

我正在编写一个 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: 2Enter your mark for subject one: 49Enter your mark for subject two: 96You have failedEnter your mark for subject one: 22Enter your mark for subject two: 100You have failedAverage for all 0 attempts is 0.00

最佳答案

您正在对变量 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);
}

关于C 程序输出不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33130295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com