有人可以帮我弄清楚为什么我的Do / While循环不起作用? (C ++)

时间:2016-02-05 08:49:18

标签: c++ windows do-while

我对C ++以及一般的编程都很陌生。我正在研究一个简单的程序,它基本上使用毕达哥拉斯定理来找到直角三角形的斜边或腿。我的主要功能差不多了,但是我遇到了让程序重新运行的一些问题。基本上,当程序询问用户是否想再次运行时,我希望它在输入“n”时关闭,如果输入“y”则再次运行。但是,无论用户输入什么,程序都会再次运行...

int a;
int b;
int c;
int form;
char ans;

do{

    cout << "Enter 1 to find the length of the hypotenuse\nEnter 2 to find the length of leg A\nEnter 3 to find the length of leg B" << endl;
    cin >> form;

    switch (form){

        // Finds length of hypotenuse
    case 1:
        cout << "\nPlease enter value of leg A" << endl;
        cin >> a;
        cout << "\nPlease enter length of leg B" << endl;
        cin >> b;
        c = sqrt((a * a) + (b * b));
        cout << "\nThe length of the hypotenuse is approximately " << c << endl;
        break;

        //Finds length of side A
    case 2:
        cout << "\nPlease enter the length of leg B" << endl;
        cin >> b;
        cout << "\nPlease enter the length of the hypotenuse" << endl;
        cin >> c;
        a = sqrt((c * c) - (b * b));
        cout << "\nThe length of leg A is approximately " << a << endl;
        break;

        //Finds length of side B
    case 3:
        cout << "\nPlease enter the length of leg A" << endl;
        cin >> a;
        cout << "\nPlease enter the length of the hypotenuse" << endl;
        cin >> c;
        b = sqrt((c * c) - (a * a));
        cout << "\nThe length of leg B is approximately " << b << endl;
        break;

    }

    cout << "\nWould you like to run the program again? Y/N\n" << endl;
    cin >> ans;

} while (ans == 'y' || 'Y');

return 0;

}

我们将非常感谢任何反馈意见,如果其中任何一项是草率和/或难以阅读,我会道歉。这是我完成的第三个快速程序,这是我第一次尝试实现一个让用户再次运行它的功能。

谢谢!

1 个答案:

答案 0 :(得分:1)

考虑ans == 'y' || 'Y'。运算符优先级指示||的优先级低于==,因此您的表达式等同于(ans == 'y') || 'Y'

Y是一个非零的char字面值,其值为非零。所以你的表达式等同于

ans == 'y' || 1

总是 1。

修复很简单:写ans == 'y' || ans == 'Y'