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."
#include<iostream>
usingnamespace 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?
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.