我正在做一个关于酒店入住的项目,但我在打印double
变量方面遇到了困难。我需要知道如何使用double
显示setprecision
变量。
#include <iostream>
using namespace std;
int main()
{
int numfloors=0; //for number of floors
int numrooms=0; //for number of rooms per floor
int numoccipied=0; //for rooms that are occupied
int TRooms=0; //for total rooms in hotel
int TOcuppied=0; //for total rooms occupied in the hotel
int TUnoccupied=0; //for unoccupied rooms in the hotel
double occupancy=0; //for persentage occupancy
cout<<"Enter the number of floors in the hotel"
<<"\nNote: please do not write value less than 1: ";
cin>>numfloors;
for(int floor=1; floor<=numfloors; floor++) //loop starts
{
cout<<"how many rooms are there in no."<<floor<<"floor?\n"; //ask user to for number of rooms per floor
cin>>numrooms;
TRooms+= numrooms; //total rooms in each floor will add and store in Trooms
cout<<"how many rooms are ocupied?\n"; //ask user to put number of occupied rooms
cin>>numoccipied;
TOcuppied+=numoccipied; //number of rooms occupied per floor is added
TUnoccupied=TRooms-TOcuppied; //stores all unoccupied rooms
occupancy=(TOcuppied)/TRooms; //store persentage occupancy
cout<<"\n\nThe Hotel has "<<TRooms<<"rooms\n";
cout<<"from which "<<TOcuppied<< " rooms are occupied,\n";
cout<<"and "<<TUnoccupied<<" are Unoccupied.\n ";
}
cout << fixed << showpoint << setprecision(1);
cout<<"\n\nOccupancy Rate: "<<occupancy*100<<"% \n\n";
return 0;
}
答案 0 :(得分:2)
您似乎是初学者,所以我会列出您的代码的一些问题:
分割两个整数时,结果也是整数。因此,在积分除法中,4/10为0.因此,该行总是产生零:
occupancy=(TOcuppied)/TRooms;
改为使用:
occupancy=(TOcuppied)/(double)TRooms;
cout
的设置显然必须在输入之前完成。所以首先发送设置:
cout << fixed << showpoint << setprecision(1);
然后:
cout << occupancy*100;
当然,你可以把它放在一行:
cout << fixed << showpoint << setprecision(1)<< occupancy*100;
您允许某些无效输出。既然你看起来很像家庭作业,你可能需要消毒那些。一个是你允许一个人进入比可用空间更多的房间:
how many rooms are there in no.1floor?
10
how many rooms are ocupied?
20
The Hotel has 10rooms
from which 20 rooms are occupied,
and -10 are Unoccupied.
Occupancy Rate: 200.00%
所以请记住检查输入:
if(numoccipied>numrooms) {
// do something, such as asking the user to enter correct value
}
同样,您应该阻止用户进入少于1层:
if(numfloors<1)
return 0;