#include "stdafx.h"#include <iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){int a, b;do{while (1){cout << "Please input two integers :";cin >> a >> b;if ((int)a != a || (int)b != b){cout << "Aren't you input two integers,please try again" << endl;continue;}else break;}if (a > b)cout << "The larger number is " << a << endl;elsecout << "The larger number is " << b << endl;} while (a = b);return 0;}執行之后如果輸入的不是整數就會重復輸出Please input two integers 與The larger number is這是為啥
3 回答

倚天杖
TA貢獻1828條經驗 獲得超3個贊

Cats萌萌
TA貢獻1805條經驗 獲得超9個贊
注釋的地方改一下就可以了,
12345678910111213141516171819202122232425262728 | #include <iostream> using namespace std; int main() { double a, b; //定義改一下 do { while (1) { cout << "Please input two integers :" ; cin >> a >> b; if (( int )a != a || ( int )b != b) { cout << "Aren't you input two integers,please try again" << endl; continue ; } else break ; } if (a > b) cout << "The larger number is " << a << endl; else cout << "The larger number is " << b << endl; } while (a == b); //改成== system ( "pause" ); return 0; } |
雖然是整數,但是你輸入可能是浮點型的,所以用double類型的作為輸入

Qyouu
TA貢獻1786條經驗 獲得超11個贊
if ((int)a != a || (int)b != b)
看起來實際想要的是檢查輸入是否正確,那么可以用if (!cin)來判斷輸入流狀態,然后用cin.clear()清除錯誤標記,cin.ignore(1024,'\n')丟棄錯誤的字符……
- 3 回答
- 0 關注
- 156 瀏覽
添加回答
舉報
0/150
提交
取消