在C++中无法打破while循环

Dan*_*mov 0 c++

我创建了一个程序,计算棱镜的体积和矩形的面积.但我想让用户决定他想用这个程序多长时间:

#include <iostream>
using namespace std;

int main()
{
    bool run = true;
    while(run = true){
        double len,width,area,volume,height;
        char check;
        cout << "Please, enter length,width and height of a prism(rectangular)!";
        cin >> len >> width >> height;
        area = width*len;
        volume = area*height;
        cout << "The area of rectangle is equal to: " << area << "\n" << "The volume of rectangular prism is equal to: " << volume << "\n";
        cout << "Do you want to try again?(y/n)\n";
        cin >> check;
        while(check != 'y'|| check != 'n'){
            cout <<"Please enter y or n\n";
            cin >> check;
        }
        if(check == 'n'){
            run = false;
            break;
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在第一部分,一切正常,但我无法摆脱这个循环:

while(check != 'y'|| check != 'n'){
                cout <<"Please enter y or n\n";
                cin >> check;
            }
Run Code Online (Sandbox Code Playgroud)

我在哪里犯了错误,我该如何解决?

Bat*_*eba 7

while (run = true)总是true,具有设定的副作用runtrue.

你想要==吗?你的编译器没有警告过你吗?更好的是,放弃重言式run == true并写下来while (run).

然后修复另一个条件while (check != 'y'&& check != 'n').想想这个:check != 'y'|| check != 'n'始终 true(如果checky,说出来的话因此它不是n).这种逻辑错误非常普遍.

最后,我不确定你真正通过引入和维护来实现的目标run.为什么不将其替换为while (true),并写return 0;到位break