Java:整数除法舍入

标签 java int percentage

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

相关文章:

Java - 在不使用外部类或方法的情况下计算数组中的重复项?

c++ - 用整数读取一行 C++

r - 如何从计数向量中计算百分比

php - 如何将百分比(例如 25%)简化为简单的陈述(例如 4 中的 1)?

r - 计算基准年和相对百分比变化的指数

Java - 在 JVM 启动时加载附加类

java - 需要在 Java 中获取开始菜单路径

Java Regex - 使用 String 的 replaceAll 方法替换换行符

c - 使用大整数数组

将十进制转换为具有长整数值的二进制 C