[英]Finding Largest And Smallest Number With UserInput ,c++
我試圖創建一個在主 function 中調用的 function 以允許用戶輸入任意數量的數字,直到輸入“0”。 使用此 function 給出輸入值的數量以及這些值的總和以及輸入的最高和最低數字。
好吧,所以假設輸入的所有數字都是整數...... SmallestNum 的 output 總是不正確的......我花了幾天時間試圖解決這個問題,但感覺我忽略或錯過了一些東西......
我錯過了什么?
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<<"\n\n"<<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
,並且 output 將為1
。
有一些問題。 在第一個輸入( count == 0
)之后,您必須設置LargestNum
和SmallestNum
。 如果退出標准為 0,則忽略 0。使用條件if (num < SmallestNum)
檢測最小數字。 arguments 通過引用傳遞。 不需要返回值。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.