gpt4 book ai didi

有人可以告诉我我的代码有什么问题并尝试解释它吗?

转载 作者:行者123 更新时间:2023-11-30 21:35:29 24 4
gpt4 key购买 nike

有人可以帮助我,因为没有循环问题。

#include <stdio.h>

int main ()
{
int counter = 0;
int average= 0;
int grade = 0;

printf("Introduce grade:");
grade=scanf("%d",&grade);
counter++;

while(grade > 0)
{
if (grade <0 && grade >100)
printf("Invalid number");
else
average +=grade;
counter++;
}

printf("average = %lf", average/counter);
}

最佳答案

可能的修复:

#include <stdio.h>

int main (void) /* it is better to add void */

{
int counter = 0;
int sum = 0; /* no average is here */
int grade = 0;
int check;


for(;;) /* make it to an infinite loop, break later */

{
/* put this block inside the loop */
printf("Introduce grade:");
check = scanf("%d",&grade); /* don't assign scanf's return variable to grade, which deletes the grade read */
if (check != 1) /* check if a integer was read */
{
puts("Invalid input. Panik!");
return 1;
}
if (grade <= 0) /* !(grade > 0) */
{
break;
}

if (grade <0 || grade >100) /* && -> || */
{
printf("Invalid number");
}
else
{
sum += grade;
counter++; /* made to be done only if grade>=0 && grade<=100 */
}
}

printf("average = %lf", (double)sum/counter); /* add cast to double */

return 0; /* it may be better to add return 0; */
}

关于有人可以告诉我我的代码有什么问题并尝试解释它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32686086/

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