2014-10-09 58 views
-3

我的小组任务是制作一个程序,允许用户输入他们想要的任意数量的数字,然后程序会告诉您输入的最高数字,输入的最低数字,输入的平均总数以及平均。我们必须使用一个菜单。输入数字,显示最高,最低,平均值和输入的数字数量。使用菜单

我们已经编写了菜单。我们的大部分计算代码都在案例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; 
} 
+0

你试过用while循环吗? – CIsForCookies 2014-10-09 21:59:31

+2

SO不是在这里解决你的功课。一个提示虽然 - 如果你想程序重复你将需要某种循环,在这种情况下,可能是一个'while'循环 – UnholySheep 2014-10-09 21:59:36

+0

谷歌搜索“while循环在C” – 2014-10-09 22:01:58

回答

0

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

bool running = 1; 

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

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

} 
0

scanf("%c", &again); - >scanf(" %c", &again);。 (增加空间)。

没有这个空间,进入 后进入num会消耗'1''2''3',但离开'\n'"%c"。通过在"%c"之前添加一个空格,scanf()将在分配charagain之前首先消耗任何空格。

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