C编程(GPA计算器)

-1 c

非常坚持这个问题.我最终得到了平均值,但它给出了负3200万或者其他东西.这是我的代码:

 #include <stdio.h>
#include <stdlib.h>


int main()
{

float fArray[30];
int choice = 0;
int x = 0;
float total = 0;
float avg = 0;

printf("1. Calculate GPA Average");
printf("\n2. Enter GPA");
printf("\n3. Quit");
printf("\n\nEnter your choice (1-3):  ");
scanf("%d", &choice);

if(choice == 2)
{
    printf("\n\nEnter GPA:  ");
    scanf("%.2f\n\n", &fArray[x]);
    total = total + fArray[x];
}
else if(choice == 3)
{
    return 0;
}
else if(choice == 1)
{
printf("The average is:  %f", total / x);
}

for(x = 1; x < 30; x++)
{
    fflush(stdin);
    int temp = 0;
    printf("1. Calculate GPA Average");
    printf("\n2. Enter GPA");
    printf("\n3. Quit");
    printf("\n\nEnter your choice (1-3):  ");
    scanf("%d", &temp);

    if(temp == 2)
    {
        printf("\n\nEnter GPA:  ");
        scanf("%.2f\n\n", &fArray[x]);
    }
    else if(temp == 3)
    {
        break;
    }
    else if(temp == 1)
    {
printf("The average is:  %f", total / x);
    }
} 

system("pause");
}
Run Code Online (Sandbox Code Playgroud)

Lar*_*ngs 6

这显然是一个家庭作业问题,你显然是一个初学者.你的老师可能会给你更好的帮助.

一些技巧:

  • 您有复制粘贴的代码.你应该摆脱程序的前半部分; 你应该只保留变量声明和循环.
  • 为了清晰起见,C程序员通常在字符串的末尾有\n,而不是下一个字符串的开头.
  • 您不应该使用"for"循环迭代'x'的值来驱动用户界面.如果用户按"1"28次计算GPA平均值,则按"2"输入等级,然后按"1"再次计算GPA平均值,即使他们只输入了等级,你也要将等级除以30一年级.你不应该迭代'x'.相反,您应该使用"while(True)"循环来驱动用户界面.只有在用户选择输入GPA时,才应增加"x".
  • 计算'total'的代码仅在第一次运行时('x'为0时)."总计"没有其他任务.现在你看到复制粘贴代码的危险吗?