c - 我该怎么做才能使我的程序在 do while 循环中保持在开关中输入的最小数字?

标签 c switch-statement do-while

我正在尝试从用户那里获取数字,他们想输入多少就输入多少。在菜单中。除了这个最低数量的东西,我已经得到了工作所需的一切。我不确定从这里去哪里。我不知道如何获得交换机中的号码。

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define PAUSE system("pause")
#define CLEAR system("cls")

main() {
    // Initialize variables
    char choice;
    int sum = 0;
    int avg = 0;
    int high = 0;
    int low = 0;
    int quit = 0;
    int i = 0;
    int num = 0;
    int j = 0;
    int prevNum;

    do{
        printf("What would you like to do\n"
        "A: enter an integer\n"
        "B: show sum\n" 
        "C: Show average\n" 
        "D: show Highest num\n" 
        "E: Show lowest\n" 
        "Q: quit\n");
        scanf("%c", &choice);
        CLEAR;

    switch (choice) {
    case 'A':
        printf("Enter an Integer\n");
        scanf("%i", &num);
        j++;
        sum = num + sum;

        if (num > high)
            high = num;

        PAUSE;
        break;

    case 'B':
        printf("The sum of al numbers entered is %i\n", sum);
        PAUSE;
        break;

    case 'C':
        avg = sum / j;
        printf("The average of all numbers entered is %i\n",avg);
        PAUSE;
        break;

    case 'D':
        printf("The Highest number entered is %i\n", high);
        PAUSE;
        break;

    case 'E':

        printf("The lowest number entered is %i\n", low);
        PAUSE;
        break;

    case 'Q':
        quit = 1;
        break;


    } // end switch

 } while (quit != 1);

PAUSE;
} // END MAIN

最佳答案

你可以只使用:

if (num < low) {
    low = num;
}

唯一的问题是第一个数字。由于您将 low 初始化为 0,因此用户输入的任何正数都不会低于此值。您需要特别对待第一个数字。您可以为此检查 j 的值。

然后在您的 A 案例中,测试这个变量。

case 'A':
    printf("Enter an Integer\n");
    scanf("%i", &num);
    j++;
    sum = num + sum;

    if (j == 1 || num > high)
        high = num;
    if (j == 1 || num < low)
        low = num;

    PAUSE;
    break;

关于c - 我该怎么做才能使我的程序在 do while 循环中保持在开关中输入的最小数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37978328/

相关文章:

c - 内存中的文件*(无磁盘访问)

javascript - Javascript 函数中的开关

java - while 循环内的 switch - 缺少 return 语句

MySQL 存储例程错误

c - 如何读取数字到文件末尾?

ios - 在 64 位处理器上运行时出现 Core Audio 错误

c - 局部静态变量如何在方法中工作?

c++ - 如何在用户数据中存储值类型?

c# - 重构长 switch 语句

java - 我的代码有什么问题吗?做 while 并 try catch