嵌套的if-else语句可能不起作用

时间:2017-09-20 06:02:20

标签: c++ if-statement control-flow

我需要一些帮助。当人数大于房间允许的最大人数时,最后一个语句不会打印。我不确定我做错了什么,或者错过了重要的项目。根据我正在使用的文本,我不认为我需要在最后一个else语句中包含一个布尔表达式,这就是为什么我没有在那里使用任何布尔表达式的原因 请协助。谢谢你的帮助

//Write a program that determines whether a meeting room is in violation of fire law regulations regarding the maximum room capacity. 
//The program will read in the maximum room capacity and the number of people to attend the meeting. If the number of people is less than 
//or equal to the maximum room capacity, the program announces that it is legal to hold the meeting and tells how many additional people 
//may legally attend. If the number of people exceeds the maximum room capacity, the program announces that the meeting cannot be held as 
//planned due to fire regulations and tells how many people must be excluded in order to meet the fire regulations.

#include <iostream>

using namespace std;

int main()
{
//variable declaration
int numberOfPeople, maxRoomCapacity, morePeople, lessPeople;

//program ask user of input
cout << "Enter the number of people to attend the meeting: ";
cin >> numberOfPeople;
cout << "What is the room capacity: ";
cin >> maxRoomCapacity;

//formula to calculate the number of people that meets fire regulation
morePeople = maxRoomCapacity - numberOfPeople;
lessPeople = numberOfPeople - maxRoomCapacity;

//if-else statement to determine if fire regulation is met
if (numberOfPeople < maxRoomCapacity)
{
    cout << "It is legal to hold the meeting in the room, plus " << morePeople
        << " additional people may legally attend the meeting." << endl;
}
else if (maxRoomCapacity = numberOfPeople)
{
    cout << "It is legal to hold the meeting in the room, no additional person can be allowed." << endl;
}
else
{
    cout << "This meeting cannot be held as planned due to fire regulations. "
        << lessPeople << " people must be excluded in order to meet the fire regulations." << endl;
}

system("pause");
return 0;
}

1 个答案:

答案 0 :(得分:2)

在您的else-if语句中,您已将numberOfPeople分配给maxRoomCapacity,而不是比较这两个变量。赋值的计算结果为true,导致if-else的主体执行,导致程序流跳过else语句。

问题在于:

else if (maxRoomCapacity = numberOfPeople)

将其更改为:

else if (maxRoomCapacity == numberOfPeople)

请注意:

  • =是一个赋值运算符
  • ==是比较运算符

编译警告(例如GCC的-Wall),你应该得到:

prog.cc: In function 'int main()':
prog.cc:26:26: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
 else if (maxRoomCapacity = numberOfPeople)
          ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~