I'm trying to get the numbers from the user, as many as they want to enter. In a menu. I have gotten everything I needed to do to work except for this lowest number thing. I'm not sure where to go from here. I don't know how I would get the number in the switch.
#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
You can just use:
if (num < low) {
low = num;
}
The only problem is the first number. Since you initialize low
to 0
, any positive number the user enters will not be lower than this. You need to treat the first number specially. You can check the value of j
for this.
Then in your A
case, test this variable.
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;
proper initialization is mandatory.
Suggest:
high
should be initialized to INT_MIN.
low
should be initialized to INT_MAX.
Note: Those macros are found in stdint.h.
then after the two lines:
if (num > high)
high = num;
insert the two lines:
if(num < low)
low = num;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.