Java:整数除法向上舍入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20041650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:36:58  来源:igfitidea点击:

Java: Integer division round up

javaintpercentage

提问by Sam Young

I'm trying to write a program that prompts the user to enter the total amount of floors in a hotel, the number of rooms in each floor, and the number of occupied rooms. In the end it should display the total # of rooms, the total # of rooms occupied, and the percentage of the rooms occupied. I am having problems with displaying the percentage of rooms occupied. I'm using all int numbers.

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

This is the equation that I put:

这是我提出的等式:

roomsOccPercentage = (totalRoomsOccupied * 100) / totalRooms ;

When I submit the program into my professor's Java runner it displays:

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

65 % of the Rooms are occupied.

But the one my professor provided outputted the answer 66 % instead so the program won't accept my file.

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

Does anyone know what I'm doing wrong? Is it a DecimalFormat error?

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

Edit: Here is the whole code

编辑:这是整个代码

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.");
    }
}

采纳答案by SudoRahul

You need to make your roomsOccPercentagea double first.

你需要先做roomsOccPercentage一个双人。

double roomsOccPercentage = 0.0;

and then cast either of the operands so avoid an integer division.

然后转换其中一个操作数,以避免整数除法。

roomsOccPercentage = (totalRoomsOccupied * 100.0) / totalRooms;

You can either use an explicit cast like (double)totalRoomsOccupiedor just make 100as 100.0which is a floating point number, thus making the division too, a floating point one and not an integer division.

您可以使用显式强制转换 like(double)totalRoomsOccupied或只是 make 100as100.0这是一个浮点数,从而使除法也成为浮点数而不是整数除法。

回答by Ruchira Gayan Ranaweera

There is nothing called rounding in integer dividing since it will take integer part only in divide result. use doublevalue for your calculations and use Math.round().

整数除法中没有所谓的舍入,因为它只会在除法结果中取整数部分。使用double值进行计算并使用Math.round().

回答by surya

Note that java plays with its own rule, You need to obey them. Decide if you want floor or ceil of the result, Follow example given below.

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

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

I hope you can now find java intresting

我希望你现在能找到有趣的 Java

回答by abrahimladha

Heres a simple way to round up:

这是一个简单的方法来四舍五入:

double dnum; = 47.213; //make this your value to round up
int inum; //null for now, will be your rounded up integer
if(dnum > (int)num)
     inum = (int)(num + 1.0);
else
     inum = (int)num;

If its not already an integer, it adds one and casts it down. If it is an integer, it casts it as an integer.

如果它还不是一个整数,它会加一并将其向下转换。如果是整数,则将其转换为整数。

回答by Matthew Mitchell

Given a/b, if you want it to round to the nearest integer, you need to add 1 if the remainder is half or more than half of b, therefore:

鉴于a/b,如果您希望它四舍五入到最接近的整数,如果余数是 b 的一半或一半以上,则需要加 1,因此:

a / b + a % b / (b/2)

Will do the trick.

会做的伎俩。

回答by user5119722

a / b + a % b / (b/2)??
1 divide by 3 should be 0
1 / 3 + 1 % 3 / (3/2) = 0 + 1 / 1 = 1which is NOT 0

a / b + a % b / (b/2)??
1 除以 3 应该是 0
1 / 3 + 1 % 3 / (3/2) = 0 + 1 / 1 = 1这不是 0

I recommend this:

我推荐这个:

(a + a % b) / b

回答by Ole V.V.

If you prefer to go into doubles to make an integer division that rounds up, you can do that. If you prefer not to, you don't need to, it's just a very slight bit tricky:

如果您更喜欢双打以进行四舍五入的整数除法,则可以这样做。如果您不想这样做,则不需要,这只是有点棘手:

private static int divideRoundUp(int denominator, int divisor) {
    return (denominator + divisor - 1) / divisor;
}

Let's try it:

让我们试试看:

    System.out.println(divideRoundUp(196, 3));
    System.out.println(divideRoundUp(197, 3));
    System.out.println(divideRoundUp(118, 2));
    System.out.println(divideRoundUp(119, 2));

This prints:

这打印:

66
66
59
60

If there's no remainder, as in 118 / 2, you get the normal result. In other cases the result is rounded up. How to handle negative denominator and/or divisor is left as an exercise for the reader, though.

如果没有余数,如 118 / 2,您会得到正常结果。在其他情况下,结果四舍五入。不过,如何处理负分母和/或除数留给读者作为练习。

In school many of us learned that 65.5 and higher should be rounded up to 66, where as numbers between 65.0 and 65.5 should be rounded down to 65. If you want this, the method is a bit different:

在学校,我们很多人都知道 65.5 和更高应该四舍五入到 66,而 65.0 和 65.5 之间的数字应该四舍五入到 65。如果你想要这个,方法有点不同:

private static int divideRoundHalfUp(int denominator, int divisor) {
    return (denominator + divisor / 2) / divisor;
}

Demonstration:

示范:

    System.out.println(divideRoundHalfUp(196, 3));
    System.out.println(divideRoundHalfUp(197, 3));
    System.out.println(divideRoundHalfUp(118, 2));
    System.out.println(divideRoundHalfUp(119, 2));

Output:

输出:

65
66
59
60