[英]finding the larger and smaller number
我正在嘗試查找更大或更小的數字,但是在最后一部分if(n1 > n2)
出問題了,如果if statement
為我提供了任意數字,那為什么不呢?
源代碼:
#include"../std_lib_facilities.h"
int main()
{
int n1=0, n2=0, num;
cout << "enter two numbers: " << '\n';
int i = 1;
while (i < 2)
{
cin >> num;
++i;
}
cout << "the first number is: "<<n1<<'\t'<<"the second number is: "<<n2<<'\n';
if (n1 < n2)
{
cout << "the smaller number is: " << n1 << '\n';
cout << "the larger number is: " << n2 << '\n';
}
if (n1 > n2)
{
cout << "the1 smaller number is: " << n2 << '/n';
cout << "the larger number is: " << n1 << '/n';
}
else
{
cout << "error" << '\n';
}
system("pause");
return 0;
}
您不是要輸入n1和n0,而是要輸入num
cin >> num;
刪除此部分:
int i = 1;
while (i < 2) {
cin >> num;
++i; }
並替換為此
cin >> n1 >> n2;
您可以輸入兩個數字,並用空格隔開
您所有的輸入將輸入num
。
拋開while
循環並編寫
cin >> n1;
cin >> n2;
代替。 還應考慮使用if
, else if
塊將終止,因為程序控制流向末尾是奇數:
if (n1 < n2) {
/*ToDo*/
} else if (n2 > n1){
/*ToDo*/
} else {
/*they are equal*/
}
或者最好還是在必須獲得兩個變量的輸入之后創建一個函數來檢查更大的函數(這實際上是問題的解決方案)。
功能:
int func_check_greater(int num1, int num2){
return (num1 > num2) ? num1 : num2;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.