【问题标题】:What can I do to make it so my programs keeps the lowest number entered in a switch in a do while loop?我该怎么做才能使我的程序保持在 do while 循环中的开关中输入的最低数字?
【发布时间】:2016-06-22 21:13:49
【问题描述】:

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

#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

【问题讨论】:

  • 你能做到最高但不能最低吗?嗯。

标签: c switch-statement do-while


【解决方案1】:

你可以使用:

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;

【讨论】:

    【解决方案2】:

    正确的初始化是强制性的。

    建议:

    high 应初始化为 INT_MIN。

    low 应初始化为 INT_MAX。

    注意:这些宏可以在 stdint.h 中找到。

    然后在这两行之后:

    if (num > high) 
        high = num; 
    

    插入两行:

    if(num < low) 
        low = num;
    

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多