简体   繁体   English

Java:整数除法

[英]Java: Integer division round up

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

Note that java plays with its own rule, You need to obey them. 请注意,java使用自己的规则,您需要遵守它们。 Decide if you want floor or ceil of the result, Follow example given below. 确定您是否需要结果的楼层或天花板,请按照下面给出的示例。

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 intresting

You need to make your roomsOccPercentage a double first. 您需要roomsOccPercentage您的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)totalRoomsOccupied or just make 100 as 100.0 which is a floating point number, thus making the division too, a floating point one and not an integer division. 您可以使用像(double)totalRoomsOccupied这样的显式(double)totalRoomsOccupied也可以将100作为100.0这是一个浮点数,从而使得除法也是浮点数,而不是整数除法。

a / b + a % b / (b/2) ?? a / b + a % b / (b/2) ??
1 divide by 3 should be 0 1除以3应为0
1 / 3 + 1 % 3 / (3/2) = 0 + 1 / 1 = 1 which is NOT 0 1 / 3 + 1 % 3 / (3/2) = 0 + 1 / 1 = 1且不为0

I recommend this: 我推荐这个:

(a + a % b) / b

There is nothing called rounding in integer dividing since it will take integer part only in divide result. 在整数除法中没有任何称为舍入的因为它只在除数结果中取整数部分。 use double value for your calculations and use Math.round() . 使用double值进行计算并使用Math.round()

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. 如果是整数,则将其强制转换为整数。

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. 会做的伎俩。

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. 如果没有余数,如在118/2中,则得到正常结果。 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. 但是,如何处理负分母和/或除数仍然是读者的练习。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM