用UserInput查找最大和最小的数字,c++

Finding Largest And Smallest Number With UserInput ,c++

本文关键字:数字 c++ UserInput 查找      更新时间:2024-09-21

im试图创建一个在主函数中调用的函数,以允许用户输入任意数量的数字,直到输入"0"。该函数给出输入的值的数量以及这些值的总和以及输入的最高和最低数字。

好的,假设所有输入的数字都是整数。。。SmallestNum的输出总是不正确。。。我花了好几天的时间试图解决这个问题,却觉得自己忽略了或错过了什么。。。

我错过了什么?

int MaxMin_Int(int& sum,int& count,int& LargestNum,int& SmallestNum)
{
int num;

do{
cout<< "Enter Number (Press 0 to Exit): ";
cin>>num;

sum = sum + num;
count++;                        //incerement count...

if ( num > LargestNum)          // Store Largest number in variable LargestNum
LargestNum = num;
else if ( num > SmallestNum && num < LargestNum )
SmallestNum = num;          //Store Smallest number in SmallestNum varaible


}while(num != 0);
count--;



return sum,count,LargestNum,SmallestNum;
}
int main(){

//decleration of static variables
int sum = 0;
int count = 0;
int LargestNum = 0;
int SmallestNum = 1;

//Loop that breaks Once User Enters '0'

// Output the sum of numbers and number of numbers entered before program was executed.
//Sum_int(count,sum);
MaxMin_Int(sum,count,LargestNum,SmallestNum);

cout<<"nn"<<count<<" Values Were Entered"<<endl;
cout<<"With a sum of: "<<sum<<endl<<endl;

// Out put Highest And Lowest Numbers


cout<<"Largest Number Entered: "<< LargestNum <<endl;
cout<<"Smallest Number Entered: "<< SmallestNum <<endl;


return 0;
}

您应该测试if ( num < SmallestNum)

此外,重新考虑SmallestNum的初始值。如果输入是7 3 12,会发生什么?所有数字都大于1,因此即使用户的输入中没有1,也不会将任何数字分配给SmallestNum,并且输出将是1

存在一些问题。在第一次输入(count == 0(之后,您必须设置LargestNumSmallestNum。如果退出条件为0,则忽略0。最小的数目是用条件CCD_ 11来检测的。参数是通过引用传递的。不需要返回值。

void MaxMin_Int(int& sum, int& count, int& LargestNum, int& SmallestNum)
{
int num;

sum = count = LargestNum = SmallestNum = 0;
do {
cout << "Enter Number (Press 0 to Exit): ";
cin >> num;

if (num != 0)
{
if (count == 0)
LargestNum = SmallestNum = num;
else if (num > LargestNum) 
LargestNum = num;
else if (num < SmallestNum)
SmallestNum = num;   
sum += num;
count++;   
}
} while (num != 0);
}