### Need help with basic hw

Hey guys, this is my first post, but I've been lurking for a while. I'm working on the following problem:

 "Write a program that calculates the occupancy rate for a hotel. The program should start by asking the user how many floors the hotel has. A loop should then iterate once for each floor. In each iteration, the loop should ask the user for the number of rooms on the floor and how many of them are occupied. After all the iterations, the program should display how many rooms the hotel has, how many of them are occupied, how many are unoccupied, and the percentage of rooms that are occupied. The percentage may be calculated by dividing the number of rooms occupied by the number of rooms."

Here's the code I've written:

 ``1234567891011121314151617181920212223242526272829303132333435`` ``````#include using namespace std; int main() { int floors, rooms, totalrooms, totaloccupied, occupied, count; count = 0; cout << "How many floors does the hotel have?\n"; cin >> floors; while (count < floors) { count++; cout << "How many rooms on floor " << count << "?\n"; cin >> rooms; cout << "How many of those rooms are currently occupied?\n"; cin >> occupied; if (occupied > rooms) { cout << "The rooms occupied cannot exceed the number of rooms.\n"; cout << "How many rooms on floor " << count << " are occupied?\n"; cin >> occupied; } totaloccupied += occupied; totalrooms += rooms; } cout << "The total amount of rooms is " << totalrooms << ".\n"; cout << totaloccupied << " rooms are occupied.\n"; cout << totalrooms - totaloccupied << " rooms are unoccupied.\n"; cout << totaloccupied / totalrooms << " perecent of the rooms are occupied.\n"; return 0; }``````

So the problem that I'm having is that "totaloccupied" and "totalrooms" are not printing their integer values. What do I do to fix this?

Thank you!
Well what are they printing? Is any outputting happening? If not, it's a problem with your loop.
totaloccupied and totalrooms are unititialized.
When you increment them at lines 26-27, you're incrementing garbage.
You need to initialize all the variables defined in this line to 0.
 `` `` ``int floors, rooms, totalrooms, totaloccupied, occupied, count;``
Regardless of what values I enter for the amount of rooms and rooms occupied, it always prints:

 The total amount of rooms is 2293601. 4199391 rooms are occupied. -1905790 rooms are unoccupied. 1 percent of the rooms are occupied.

Try initializing them all to 0 explicitly. If the problem persists, your loop is broken.
That worked! Thanks man.
Just one question. Why?
Because C++ isn't as nice as other languages. When you declare a variable, it is given a place in memory, and generally won't initialize to a default value. So chances are these variables will have a value, that value being whatever garbage happens to be in that place of memory.

The moral of the story, always initialize variables before using them.
Topic archived. No new replies allowed.