首页 > 解决方案 > 为什么无论输入如何,所有 if-else 语句都会打印?

问题描述

当输入任何字母(F、R 或 G)时,每个 if 语句都会在编译器中打印。我不确定为什么会这样,但有些答案会很好!

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
int tmp;
float precip;
char frg;

cout << "Fall 2018 Automated \"Bruin\" Golf Course Sprinkler System" << endl;
cout << endl << "What is the temperature in degrees(F)? ";
cin >> tmp;
cout << "How much precipitation today (in inches)? ";
cin >> precip;
cout << "The Golf Course grass divisions are F-Fairways, R-Rough, G-Greens.";
cout << endl << "Which do you choose (FRG)? ";
cin >> frg;

if (frg == 'R' && precip < 0.835 && tmp > 38)
    {
        cout << endl << "Given the temperature is " << tmp << " degrees and " << precip << " inches of precipitation today." << endl;
        cout << "The Rough on the Golf Course will be watered.";
    } else
        {
            cout << endl << "Given the temperature is " << tmp << " degrees and " << precip << " inches of precipitation today." << endl;
            cout << "The Rough on the Golf Course will NOT be watered.";
        }

if (frg == 'F' && precip < 0.525 && tmp > 38)
    {
        cout << endl << "Given the temperature is " << tmp << " degrees and " << precip << " inches of precipitation today." << endl;
        cout << "The Fairways on the Golf Course will be watered.";
    } else
        {
            cout << endl << "Given the temperature is " << tmp << " degrees and " << precip << " inches of precipitation today." << endl;
            cout << "The Fairways on the Golf Course will NOT be watered.";
        }

if (frg == 'G' && precip < 0.325 && tmp > 38)
    {
        cout << endl << "Given the temperature is " << tmp << " degrees and " << precip << " inches of precipitation today." << endl;
        cout << "The Greens on the Golf Course will be watered.";
    } else
        {
            cout << endl << "Given the temperature is " << tmp << " degrees and " << precip << " inches of precipitation today." << endl;
            cout << "The Greens on the Golf Course will NOT be watered.";
        }
return 0;
}

即使当我在询问 frg 变量时输入 R 时,所有 if 语句都会在编译器中打印。请帮忙!

谢谢你。

标签: c++if-statement

解决方案


打印所有 if 语句

这不是正在发生的事情。只有一个if语句被打印,但其他 2 个else语句(来自其他 2 ifs)也被打印,因为if它将失败。

我对你的代码做了一些评论。

if (frg == 'R' && precip < 0.835 && tmp > 38) {
    // ... your code
} else {
    // Execution will reach this block when frg != R || precip > 0.835 || tmp < 38
    // So if you typed F or G, this else will be executed
}

if (frg == 'F' && precip < 0.525 && tmp > 38) {
    // ... your code
} else {
    // Execution will reach this block when frg != F || precip > 0.525 || tmp > 38
    // So if you typed R or G, this else will be executed
}

if (frg == 'G' && precip < 0.325 && tmp > 38) {
    // ... your code
} else {
    // Execution will reach this block when frg != G || precip > 0.325 || tmp < 38
    // So if you typed R or F, this else will be executed
}

至于你应该做什么来“解决”这个问题,我真的无法提出任何建议,因为我不知道所需的行为是什么。

希望这可以解决问题,

干杯。


推荐阅读