gpt4 book ai didi

c++ - 我如何在 for 循环内部或外部打印双变量

转载 作者:行者123 更新时间:2023-11-30 03:34:48 24 4
gpt4 key购买 nike

我正在做一个关于酒店入住率的项目,但我在打印 double 变量时遇到了困难。我需要知道如何使用 setprecision 显示 double 变量。

#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;
}

最佳答案

您似乎是初学者,所以我将列出您的代码的一些问题:

  1. 当两个整数相除时,结果也是一个整数。因此,在整数除法中,4/10 为 0。因此,此行始终生成零:

    occupancy=(TOcuppied)/TRooms;

    改为使用:

    occupancy=(TOcuppied)/(double)TRooms;
  2. cout 的设置显然必须全部在输入之前进行。所以首先发送设置:

    cout << fixed << showpoint << setprecision(1);

    然后:

    cout << occupancy*100;

    当然也可以放在一行中:

    cout << fixed << showpoint << setprecision(1)<< occupancy*100;
  3. 您允许某些类型的无效输出。由于您的作业看起来很像家庭作业,因此您可能需要对它们进行清理。一种是您允许一个人进入比可用房间更多的房间:

    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
    }

    同样,你应该阻止用户进入不到一层楼:

    if(numfloors<1)
    return 0;

关于c++ - 我如何在 for 循环内部或外部打印双变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41753982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com