使用用户输入查找最大和最小数字 [英] Finding biggest and smallest numbers using user input
问题描述
在一组数字中找到最大和最小的数字是一个问题,但是我们不知道用户想要多少个数字-
Well it is a problem about finding the biggest and smallest number in a group of numbers, but we do not know how many numbers the user wants-
到目前为止,这是我所做的:
So far this is what i have done:
#include <stdio.h>
#include <conio.h>
int main()
{
int num;
int i;
int maxi=0;
int minim=0;
int cont = 0;
printf ("\nQuantity of numbers?: ");
scanf ("%d", &num);
while (num>0)
{
printf ("\nEnter number:");
scanf ("%d", &i);
if (num>i)
minim=i++;
else
if (i>num)
max=i++;
cont++;
}
printf ("\nBiggest number is es: %d", maxi);
printf ("\nSmallest number is: %d", minim);
getch();
return 0;
}
我做了我的程序,询问用户要输入多少个数字,然后我使程序读取它们,但是当它读取最大或最小的数字时,有时会变为小而最大,而不会读取负数.
I did my program to ask how many numbers the user will want to put and i made the program to read them, BUT when it reads the biggest or/and smallest numbers it will sometimes changes biggest with small and it will not read negative numbers.
我如何做才能使我的程序更好?
How do i do to make my program better?
推荐答案
您应将 mini
初始化为可能的最大整数,即 INT_MAX
和 maxi
到最小的int,即 INT_MIN
.这样,即使第一个数字为负,也将考虑使用 maxi
,如果第一个数字为正,则仍将考虑使用 mini
.常量 INT_MAX
和 INT_MIN
包含在< climits>
或< limits.h>
中.
You should initialize mini
to the largest possible int, i.e. INT_MAX
and maxi
to the smallest possible int, i.e., INT_MIN
. This way, even if the first number is negative, it will be considered for maxi
, and if the first number is positive it will still be considered for mini
. The constants INT_MAX
and INT_MIN
are included in <climits>
or <limits.h>
.
此外,您正在将当前输入的数字与 num
(这是用户输入的数字的计数器)进行比较,而不是他要比较的值之一.更好的修改代码是:
Also, you are comparing the current entered number with num
, which is the counter of numbers entered by user, not one of the values he wants to compare. A better modified code would be :
#include<limits.h>
#include<stdio.h>
int main()
{
int num;
int maxi=INT_MIN; //initialize max value
int mini=INT_MAX; //initialize min value
int temp;
scanf("%d", &num); //take in number of numbers
while(num--) //loop "num" times, num decrements once each iteration of loop
{
scanf("%d", &temp); //Take in new number
if(temp>maxi) //see if it is new maximum
maxi=temp; //set to new maximum
if(temp<mini) //see if new minimum
mini=temp; //set to new minimum
}
printf("\nMaxi is:\t%d\nMini is:\t%d\n", maxi, mini); //print answer
return 0;
}
这篇关于使用用户输入查找最大和最小数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!