0

我必须编写一个程序,使用 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;
}   
4

3 回答 3

0

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

于 2013-10-29T03:30:02.267 回答
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;
于 2013-10-29T02:59:34.723 回答
0

您应该初始化诸如total_occupy = 0等变量...否则您可能会得到意想不到的结果。

问候

于 2013-10-29T03:02:32.940 回答