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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值