为什么无论输入如何,所有 if-else 语句都会打印?

Why are all if-else statements printing no matter the input?

本文关键字:语句 if-else 打印 所有 输入 为什么      更新时间:2023-10-16

当输入任何字母(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 语句也会打印在编译器中。请帮忙!

谢谢。

打印所有 if 语句

这不是正在发生的事情。仅打印if语句中的一个,但还会打印其他 2 个else语句(来自其他 2 个语句if(,因为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
}

至于你应该怎么做来"修复"这个问题,我真的不能提出任何建议,因为我不知道所需的行为是什么。

希望这能解决问题,

干杯。

你的逻辑似乎是正确的,它应该只进入基于你的输入字符的 if 语句之一。 你确定它没有击中一个 IF 然后击中其他 2 个吗?

您可以添加

return;

到最后,你是 { } 括号内的逻辑,这将确保只有一个逻辑 { } 括号会执行......

或者你需要一个嵌套的 if/else 语句来确保只执行 1 { } 括号。

就像你现在一样,你运行 1 个 if,然后根据角色运行 2 个其他