我遇到了一個與我的程序有關的問題。我正在構建一個金字塔程序,以更好地理解C++中的循環結構。 的問題是,當我建立並運行此,我得到:Do While While:永不停止的循環問題
cout << "\nPlease enter the number of lines for your pyramid: ";
cin >> height;
,我輸入一個隨機字符,如「K」,它不斷地啓動(上房)循環:
cout << "ERROR: Please enter a value between 3 and 25!" << endl;
我的問題:爲什麼它不斷循環? 有什麼可以實施來解決這個問題?
#include <iostream>
#include <limits>
using namespace std;
void draw(int height)
{
for(int line = 0;line<=height;line++)
{
int spaces = height - line;
for(int j=1;j<=spaces;j++)
cout<<" ";
for(int i=1;i<=line*2+1;i++)
cout<<"+";
cout<<"\n";
}
}
int main()
{
int height;
do{
cout << "\nPlease enter the number of lines for your pyramid: ";
cin >> height;
if(height>3 && height<25)draw(height);
else{
cout << "ERROR: Please enter a value between 3 and 25!" << endl;
}
}while(height<3 || height>25);
cout << "\n";
return 0;
}
我已經研究並沒有發現類似的問題,最常見的問題似乎是人們不設置他們的條件。
你是不是測試的讀取輸入的結果。 – chris
你期待一個'int',你爲什麼輸入'K'? – herohuyongtao
@herohuyongtao - 用戶有時會輸入錯誤的東西 –