C++循环判断三角形,直到输入正确为止

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yxswhy/article/details/82878362

这个是运行正确的,循环直到用户输入正确的。

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函数输出的自动变量

猜你喜欢

转载自blog.csdn.net/yxswhy/article/details/82878362