使用for循环从多个输入中获取总和?

时间:2013-10-29 02:58:00

标签: c++ for-loop sum

我必须编写一个程序,使用for循环询问酒店楼层数,然后询问用户每层楼的房间数量和占用的房间数量。最后,我要将所有房间加起来,占用多少房间,不占用房间,并根据这些数字给出百分比。到目前为止,我所拥有的只是循环,而我的总和功能现在给了我惊人的数字。

#include <iostream>

using namespace std;

int main ()

{

int floor, room, occupy, total_unoccupy, total_occupy, total_room;

cout << "How many floors are in the hotel?\n";
cin >> floor;


   for ( ;floor >= 1; floor--)
   {
      cout << "How many rooms are on floor " << floor <<  "?" << endl;
      cin >> room;
      cout << "How many of these rooms are occupied?" <<endl;
      cin >> occupy;
   }
total_room += room;

cout << "The total number of rooms are " << total_room << "." << endl;


return 0;
}   

3 个答案:

答案 0 :(得分:0)

total_room += room;循环中移动for

for ( ;floor >= 1; floor--) {
    cout << "How many rooms are on floor " << floor <<  "?" << endl;
    cin >> room;
    total_room += room;
    cout << "How many of these rooms are occupied?" <<endl;
    cin >> occupy;
    total_occupy += room;
    total_unoccupy += room-occupy;
}

此外,您需要更改此行:

int floor, room, occupy, total_unoccupy, total_occupy, total_room;

对此:

int floor = 0, room = 0, occupy = 0, total_unoccupy = 0, total_occupy = 0,  total_room = 0;

答案 1 :(得分:0)

您应该初始化 total_occupy = 0 等变量...否则您可能会产生意外结果。

此致

答案 2 :(得分:0)

感谢nhgr,没有什么可以回答的 此外,在乘法运算的情况下,您需要将总变量初始化为1.