【问题标题】:c++ program runs incorrect else statementc++程序运行不正确的else语句
【发布时间】:2019-03-18 01:21:56
【问题描述】:

当我运行程序时,我无法弄清楚为什么当我要求输入字母 a、b 或 c 并且输入了其他字母之外的其他字母时,为什么会出现“无效标准”而不是“输入了无效的代码。当我输入超出范围的数字时,它会转到“输入了无效的数字”,但不是在我要求输入字母时

#include <iostream>
#include <iomanip>
#include "Header.h"

using namespace std;

int main()
{
    head();

    int num_1, a, b, c;
    char char_1;
    float num_2;
    num_2 = 28.82;

    a = b = c = 0;

    cout << "Please enter a number between 10 and 30." << endl;
    cin >> num_1;

    if (num_1 >= 10 && num_1 <= 30)
    {
        cout << "Enter the letter a, b, or c." << endl;
        cin >> char_1;

        if (char_1 == 'a'||'b'||'c')
        {

            if ((num_1 >= 10 && num_1 <= 20) && (char_1 == 'a'))
            {

                num_2 = num_2 + .5;
                cout << fixed << setprecision(1) << num_2 << endl;

            }
            else if ((num_1 >= 19 && num_1 <= 30) && (char_1 == 'b'))
            {
                num_2 = num_2 + .10;
                cout << fixed << setprecision(2) << num_2 << endl;

            }
            else if ((num_1 >= 19 && num_1 <= 30) && (char_1 == 'c'))
            {
                num_2 = num_2 + .100;
                cout << fixed << setprecision(3) << num_2 << endl;
            }
            else
            {
                cout << "Invalid criteria" << endl;

            }


        }
        else 
            cout << "An invalid code has been entered." 


    }

    else
        cout << "An invalid number has been entered." << endl;




    system("pause");
    return 0;
}

【问题讨论】:

    标签: c++ if-statement


    【解决方案1】:

    表达式:

    char_1 == 'a' || 'b' || 'c'
    

    相当于:

    char_1 == ('a' || 'b' || 'c')
    

    因此首先计算所有被视为布尔值的字母的逻辑或(全部为真,因此结果为真),然后将 that 与您的变量进行比较。

    你需要的是:

    (char_1 == 'a') || (char_1 =='b') || (char_1 =='c')
    

    这会根据每个的可能性检查角色,然后确定其中任何一个是否为真。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 2012-06-08
      • 2019-08-28
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      相关资源
      最近更新 更多