输入数字,显示最高,最低,平均和输入的数字。使用菜单

时间:2014-10-09 21:55:49

标签: c

我的小组分配是制作一个程序,允许用户输入任意数量的号码,然后程序会告诉您输入的最高号码,输入的最低号码,平均值,输入的总数量以及平均值。我们必须使用菜单。

我们写了菜单。我们在案例A中有大部分计算代码(我们必须使用字母)来计算东西。但我们不知道如何重复该程序。如果您已完成输入数字并将N说成"您是否要输入另一个号码",程序就会关闭。

另外,您将如何计算总数?

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define pause system("pause")
#define cls system("cls")
#define pause system("pause")
#define flush fflush(stdin)
#include <ctype.h> // contains toupper

main(){

int num, count = 0, high = 0, low = 0, total = 0;
float avg;
char choice = ' ', again;

printf("\t\t      =====================\n");
printf("\t\t      ==    MAIN MENU    ==\n");
printf("\t\t      =====================\n");
printf("\t\tA. Enter a number.\n");
printf("\t\tB. Display the highest number.\n");
printf("\t\tC. Display the lowest number.\n");
printf("\t\tD. Display the average of all numbers.\n");
printf("\t\tE. Display how many numbers were entered.\n");
printf("\t\tQ. Quit.\n\n\n");
printf("Enter your selection: ");
scanf("%c", &choice);


    switch (choice) {
    case 'A':
        do {
            printf("Enter a number: ");
            scanf("%i", &num);
            if (count = 0)  {
                high = num;
                low = num;
            }
            else
            if (num > high)
                num = high;
            if (num < low)
                num = low;
            count++;

            printf("Do you want to enter another number? (Y/N):  ");
            scanf("%c", &again);
        } while (again != 'N');
        break;
    case 'B':
        if (count == 0) { printf("Please enter a number first.\n\n"); 
            }
        else printf("The highest number is %i\n\n", high);
        break;
    case 'C':
        if (count == 0) printf("Please enter a number first.\n\n");
        else printf("The lowest number is %i\n\n", low);
        break;
    case 'D':
        if (count == 0) printf("Please enter a number first.\n\n");
        else
            avg = total / count;
            printf("The average is %.2f\n\n", avg);
        break;
    case 'E':
        printf("You entered %i numbers.\n\n", count);
        break;
    case 'Q':
        printf("Thanks for playing.\n\n");
        break;
    default:
        printf("Invalid Selection.\n\n");
        break;
    }
    pause;
}

2 个答案:

答案 0 :(得分:0)

您需要包含另一个封装switch语句的while循环

bool running = 1;

while(running)
{
    printf("Enter your selection: ");
    scanf("%c", &choice);

    switch(choice)
    {
        ...
        case 'q':
        case 'Q':
            running = 0;
            break;
    }

}

答案 1 :(得分:0)

scanf("%c", &again); - &gt; scanf(" %c", &again);。 (添加空格)。

没有该空格,输入 1 2 3 输入后,num将消耗'1''2''3',但保留'\n' "%c"。通过在"%c"之前添加空格,scanf()将首先消耗任何空格,然后再将char分配给again

  scanf("%i", &num);
  ...
  printf("Do you want to enter another number? (Y/N):  ");
  // scanf("%c", &again);
  scanf(" %c", &again);
} while (again != 'N');