Почему все операторы if-else печатают независимо от ввода? - PullRequest
0 голосов
/ 04 октября 2018

При вводе любой буквы (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;
}

Даже когда я вводил R при запросе переменной frg, все операторы if печатались в компиляторе.Пожалуйста помоги!

Спасибо.

Ответы [ 2 ]

0 голосов
/ 04 октября 2018

ваша логика кажется правильной, она должна входить только в один из операторов if на основе вашего входного символа.Вы уверены, что это не ударяет по одному IF, а затем по другим 2 ПРОБЛЕМ ??

Вы можете добавить

 return;

в конец логики внутри скобок {}, чтоубедитесь, что выполняется только одна логическая скобка {} ...

, иначе вам понадобится вложенный оператор if / else, чтобы убедиться, что выполняется только 1 {} скобка.

в том виде, как он у вас естьтеперь вы запускаете 1 if, а затем 2 elses в зависимости от персонажа

0 голосов
/ 04 октября 2018

Все операторы if напечатаны

Это не то, что происходит.Только один из операторов if напечатан, но другие 2 else операторы (из других 2 if s) также напечатаны, потому что 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
}

Что касается того, что вы должны сделать, чтобы «исправить» это, я не могу ничего предложить, потому что я не знаю, каково желаемое поведение.

Надеждаэто проясняет ситуацию,

Приветствия.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...