首页 文章

当我以不同的顺序输入值时,程序会出错

提问于
浏览
-3

我正在尝试确定用户输入程序的值是有效还是无效

以下是有效的条件:

  • 退出角度必须介于-10和50之间

  • 发病率值必须介于-3和3之间

  • 给出等式

range =(36 - 0.45(出口角度))/(入口角度 - 出口角度)

范围必须介于0.75和1.25之间 .

用户输入-1 -1 -1退出程序

输入如下:[入射角,出射角,入射角] . 在程序中输入数字时,不使用逗号 .

问题:

鉴于上述条件,当我输入值集[50,-9.999,0]时,程序说这是无效的 . 这个答案是对的 . 如果将值输入上面的等式,则范围为0.675004,这超出了域 .

如果我输入一组值[41.6,-10.01,1],程序会说它无效 . 这个答案是正确的,因为-10.01不在退出角度范围内 . 之后,当我输入[50,-9.999,0]时,程序突然认为这个有效 . 此答案不正确,因为范围不属于域 .

代码

#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstdlib>

using namespace std;

int main (void) {
    // Declare variables
    double entry = 0.0;
    double exit = 0.0;
    double incidence = 0.0;
    double range = 0.0;
    bool validExit = false;
    bool validIncidence = false;
    bool validRange = false;

    do
    {
        // Prompt user to enter input values
        cout << "Enter flow entry angle, flow exit angle, and incidence: ";
        cin >> entry >> exit >> incidence;

        // Check if exit angle is valid
        if (exit >= -10.0 && exit <= 50.0) {
            validExit = true;
        }
        else {
            validExit = false;
        }

        // Check if incidence is valid
        if (incidence >= -3.0 && incidence <= 3.0) {
            validIncidence = true;
        }
        else {
            validIncidence = false;
        }

        // Determine range if difference between entry and exit value is greater than 0.0001
        if (fabs(exit - entry) > 0.0001)
        {
            range = (36 - (0.45 * exit))/(entry - exit);

            // Check if range is valid
            if (range >= 0.75 && range <= 1.25)
            {
                validRange = true;
            }
        }
        else {
            validRange = false;
        }

        // Print output
        if ((validExit != true) || (validIncidence != true) || (validRange != true)) {
            cout << "Invalid entries ignored" << endl;
        }
        else {
            cout << "Valid" << endl;
        }

    // Loop until user enters -1, -1, -1
    } while (entry != -1.0 && exit != -1.0 && incidence != -1.0);

    system("PAUSE"); return 0;

}

2 回答

  • 1

    您需要在do-while循环开始时将validRange重新初始化为false . 否则,一旦输入有效范围,它将保持范围有效,直到(fabs(exit - entry)> 0.0001)为假 .

  • 1

    检查中有一条路径没有设置validRange的方式:即 (abs(exit - entry) > 0.0001) 为真但 if (range >= 0.75 && range <= 1.25) 为false时 . 因此,validRange仍然具有上一次迭代剩余的任何值 .

相关问题