gpt4 book ai didi

Java:整数除法舍入

转载 作者:搜寻专家 更新时间:2023-11-01 01:00:28 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,提示用户输入旅馆的总楼层数、每层的房间数以及已入住的房间数。最后,它应该显示房间总数、已占用房间总数以及已占用房间的百分比。我在显示房间占用百分比时遇到问题。我正在使用所有 int 数字。

这是我提出的等式:

roomsOccPercentage = (totalRoomsOccupied * 100) / totalRooms ;

当我将程序提交到教授的 Java 运行程序时,它显示:

65 % of the Rooms are occupied.

但是我的教授提供的答案输出了 66%,所以程序不会接受我的文件。

有谁知道我做错了什么?是 DecimalFormat 错误吗?

编辑:这是整个代码

import java.util.Scanner; 
import java.text.DecimalFormat;

public class hw7_1 {
public static void main(String[]args) {

Scanner keyboard = new Scanner(System.in);
DecimalFormat formatter = new DecimalFormat("#0");
int totalFloors;
int totalRooms = 0;
int numFloors;
int numRooms;
int roomsOccupied;
int totalRoomsOccupied = 0;
int roomsOccPercentage = 0;

//prompting users to input # of floors, no inputs below 1 floor
do {
System.out.println("Please enter the number of floors in the hotel: ");
numFloors = keyboard.nextInt();

if (numFloors < 1) {
System.out.println("You have entered an invalid number of floors. ");
}
}
while (numFloors < 1);

//for loops on how many rooms on each hotel floors
for ( int Floors = 1; Floors <= numFloors; Floors++) {
if (Floors == 13 ) {
continue;
}

do {
System.out.println("Please enter the number of rooms on floor #: " + Floors );
numRooms = keyboard.nextInt();

if (numRooms < 10) {
System.out.println("You have entered an invalid number of rooms. ");
}
} while (numRooms < 10);

System.out.println("Please enter the number of occupied rooms on floor #: " + Floors);
roomsOccupied = keyboard.nextInt();

totalRooms = totalRooms + numRooms;
totalRoomsOccupied = totalRoomsOccupied + roomsOccupied;
roomsOccPercentage = (totalRoomsOccupied * 100) / totalRooms ;
}
System.out.println("\nThe hotel has a total of " + totalRooms + " rooms.");
System.out.println(totalRoomsOccupied + " of the rooms are occupied.");
System.out.println(formatter.format(roomsOccPercentage) + "% of the rooms are occupied.");
}
}

最佳答案

注意java有它自己的规则,你需要遵守它们。决定你是想要结果的 floor 还是 ceil,按照下面给出的例子。

double roomsOccPercentage;
roomsOccPercentage =Math.ceil((double)5/4); //will be 2
roomsOccPercentage =Math.ceil(5/4); //will be 1
roomsOccPercentage =Math.floor((double)5/4); //will be 1

我希望你现在能对 java 感兴趣

关于Java:整数除法舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20041650/

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