...

View Full Version : TypeCasting



pbracing33b
10-27-2012, 12:23 AM
I have a program that is suppose to find the percentage of occupied rooms in the hotel. I have most of my program running, but when I try to typecast my percentage the percentage isn't coming out right and I am not sure as to why.
Can someone please take a look at my code to see why this isn't working?


#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
//Varibles
int occupied = 0,floors = 0,rooms = 0, heartBreak = 0;
int percentage = 0, total = 0, occupiedTotal = 0,unoccupied = 0, unoccupiedTotal = 0;
int mostempty = 0, HBfloor;

//Input
cout << "How many floors does the hotel have? ";
cin >> floors;

while (floors < 1 ) // Validate input
{
cout << "Please enter floors greater than or equal to ten.\n";
cout << "How many floors does the hotel have? ";
cin >> floors;
}

//Run a for loop to get the amount of rooms, and it's occupancy rate!
for (int cnt = 1; cnt<=floors; cnt++)
{
if (cnt == 2)//Skip Floor two
{
continue;
}

cout << "How many rooms are on floor "<<cnt<<"?";
cin >> rooms;


while (rooms < 10) // Validate input
{
cout << "Please enter rooms greater than or equal to ten.\n";
cout << "How many rooms are on floor "<<cnt<<"?";
cin >> rooms;
}
total += rooms;//Accumulator

cout<<"How many of those are occupied?";
cin>> occupied;


while(occupied > rooms)//validate input
{
cout<<"Error, Number of occupied rooms cannot exceed rooms listed \n";
cout<<"How many of those are occupied?";
cin>> occupied;
}
occupiedTotal += occupied;//Accumulator
unoccupied = rooms - occupied;
if (unoccupied > mostempty)//find the floor with the least amount of rooms occupied
{
mostempty = unoccupied;
HBfloor = cnt;
}



}

//Processing Section
unoccupied = total - occupiedTotal;
percentage = (double)total/ occupiedTotal;

//output
cout<<"The hotel has a total " <<total<< " rooms!"<<endl;
cout<<occupiedTotal<< " are occupied."<<endl;
cout<<unoccupied<<" are empty."<<endl;
cout << fixed << showpoint << setprecision(1);
cout<<"The occupancy rate is "<<percentage<<"%"<<endl;
cout<<"The heartbreak floor is "<<HBfloor<<" with "<<mostempty<<" empty rooms." <<endl;
system("pause");
return 0;
}

Spookster
10-27-2012, 01:04 AM
This doesn't make sense. You would see why this isn't working if you run it in a debugger and look at what is happening with each value.

percentage = (double)total/ occupiedTotal;

Why are you using int type here for all 3 variables? And why are you trying to typecast one of them?

pbracing33b
10-27-2012, 01:31 AM
Sorry I forgot to change that I was playing with it earlier and forgot to change it back, but it didn't work the other way around either it should've been this to (and was to begin with) :
percentage = occupiedTotal/ (double)total;

I initially did have all doubles but my teacher wanted me to typecast it!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum