首页 > 解决方案 > C 程序是一个菜单并使用 switch case。到目前为止,选项 A,输入 GPA 有效,但对于选项 B,平均值是错误的

问题描述

这是我正在尝试制作的程序的描述。选项 A 有效,但是当我之后输入选项 B 时,平均值完全错误。

描述:这是一个菜单驱动程序,用户必须在其中选择他们想要的选项。有选项八个选项。选项 A 将让用户输入 GPA。选项 B 将显示所有 GPA 的平均值。选项 C 将显示最高 GPA。选项 D 将显示最低 GPA。选项 E 将显示调整后的平均值。选项 F 将查看是否输入了某个 GPA。选项 G 显示数组的内容。选项 Q 将退出程序。

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

int main()
{
    float gpa[1000]; //this is the array for all the GPAs the user enters
    char choice; 
    int i;
    float n;
    float sum = 0;
    float average = 0;

    while (1)
    {
        printf("\n\nChoose one of the following");
        printf("\nA.Enter GPA");
        printf("\nB.Display Average of all GPA's");
        printf("\nEnter your selection: ");
        scanf_s(" %c", &choice);

        //user enters in GPAs and it gets put into array
        switch (choice)
        {
        case 'A':
            printf("\nHow many GPAs are you entering?: ");
            scanf_s("%f", &n);
            for (i = 1; i <= n; i++)
            {
                printf("\nEnter GPA: ");
                scanf_s("%f", &gpa[i]);
                if (gpa[i] < 2.0)
                {
                    printf("You need to study harder.");
                }
                if (gpa[i] > 3.5)
                {
                    printf("Nice work.");
                }
            }
        }

        //GPAs from the array are added up and divided by n, how many GPAs 
        switch (choice)
        {
        case 'B':
            for (i = 0; i < n; i++)
            {
                sum += gpa[i];
            }

            average = sum / n;
            printf("The average is: %.2f", average);
        }
    }

    return 0;
}

标签: c

解决方案


注意 C 中“switch-case”的语法:

  switch (choice)
  {
    case 'A': {
      // some work for A choice..
      break;
    }
    case 'B': {
      // some work for B choice..
      break;
    }
    default:
      // print "Error in input" or something
      break;
  } 

让我们标记一些要点:

  1. “选择”变量只有 1 个开关。

  2. 每个案例的结尾都必须以“break;”结尾 除非,您将陷入下一个案例。

  3. 对于这些情况,您不必使用“{ }”,但我建议从视觉原因。

  4. 我还建议在最后使用“默认”以处理所有情况。如果“选择”不是“A”而不是“B”,您将默认登陆

我也认为你的'n'变量应该是int,因为它是一个整数。我已经看到有人发现了你的错误,祝你好运:)


推荐阅读