C++迴圈判斷三角形,直到輸入正確為止
這個是執行正確的,迴圈直到使用者輸入正確的。
int main(int argc, _TCHAR* argv[]){
int a, b, c, sum;
cout<<"please input thelength of the triangle"<<endl;
cin>>a>>b>>c;
while(!((a+b)>c && (a+b)>c && (a+b)>c)){
cout<<"the number cannt became a triangle, please input agin"<<endl;
cin.clear();
cin>>a>>b>>c;
sum = a+b+c;
}
cout<<"This is a triangle!\n";
//
if(a==b==c)
cout<<"等邊三角形";
else if(a==b || b==c || a==c)
cout<<"等腰三角形";
else if((c*c == a*a + b*b)||(a*a == c*c + b*b)||(b*b == a*a + c*c))
cout<<"直角三角形";
else
cout<<"普通三角形";
cout<<"sum: "<<sum<<endl;
system("pause");
return 0;
}
錯誤示範以及問題解釋:
int main(){
int a, b, c, sum;
bool stand;
cout<<"please input thelength of the triangle"<<endl;
cin>>a>>b>>c;
stand = (a+b)>c && (a+b)>c && (a+b)>c;
while(!stand){
cout<<"the number cannt became a triangle, please input agin"<<endl;
cin.clear();
cin>>a>>b>>c;
stand = (a+b)>c && (a+b)>c && (a+b)>c;
sum = a+b+c;
}
cout<<"This is a triangle!\n";
//
if(a==b==c)
cout<<"等邊三角形";
else if(a==b || b==c || a==c)
cout<<"等腰三角形";
else if((c*c == a*a + b*b)||(a*a == c*c + b*b)||(b*b == a*a + c*c))
cout<<"直角三角形";
else
cout<<"普通三角形";
cout<<"sum: "<<sum<<endl;
system("pause");
return 0;
}
出現問題的嘗試,將條件(a+b)>c && (a+b)>c && (a+b)>c賦值給一個布林型變數 stand,但是輸出stand無法更新,如果第一次輸入錯誤,再次輸入正確,也會一直在那個迴圈裡,因為那個外部的stand值沒有更新。為什麼會沒有更新呢。
變數都是存入棧中的,在while迴圈裡面stand生命週期只在迴圈裡面,出來了,記憶體就別釋放了,也就是說while()裡的條件找不到迴圈內的區域性變數值,只有之前外部的stand值,所以一直都是第一次輸入時候的值。
舉個例子:
void main(){
int a=20;
if(ture){
int a= 10;
cout<<a<<endl;
}
cout<< a<<endl;
}
結果為
10 是if迴圈中輸出的自動變數
20是main函式輸出的自動變數