簡體   English   中英

Java雙精度錯誤轉換為int

[英]Java double incorrect cast to int

當我嘗試將double轉換為int時。 我的變量“ check”始終等於零。 但是,如果我在psvm中做到這一點。 如果我在課堂上這樣做,檢查總是等於零。 我該如何解決這個問題? 我嘗試使用Double和Integer進行強制轉換,但它也不起作用。

我在Ubuntu 18上使用java 11。

public class Round {

    public int round (double value) {
        return (value > 0) ? roundPositiveNubmer(value) : roundNegativeNumber(value);
    }

    private int roundPositiveNubmer(double value) {
        int result;
        double checkD = value * 10 % 10;
        int check = (int) checkD;
        if (check > 5) {
            value++;
            result = (int) value;
        } else {
            result = (int) value;
        }
        return result;
    }

    private int roundNegativeNumber(double value) {
        int result;
        double checkD = value * 10 % 10;
        int check = (int) checkD;
        if (check > -5 && check < 0) {
            value--;
            result =  (int) value;
        } else {
            result =  (int) value;
        }
        return result;
    }
}

當我嘗試將23.6舍入時。 我有23歲,但必須24歲。

JB Nizet已經在注釋中暗示了,您的代碼在肯定的情況下效果很好。

麻煩在於否定情況。 round(-23.6)得出-23,而不是-24。 這是由以下行引起的:

    if (check > -5 && check < 0) {

在-23.6的情況下, check值為-6, 小於 -5。 我想您想要更簡單的方法:

    if (check < -5) {

現在,-23.6舍入為-24。 -23.5仍舍入為-23。 如果您在這種情況下也想要-24:

    if (check <= -5) {

在肯定的情況下,您可能還需要考慮是否要>=

或者只是使用Math.round()

Sourabh Bhat的評論也正確:您正在重新發明輪子。 Math.round()已經完成了舍入方法的工作。 因此,如果您將此編碼為練習,那么很好,您正在學習,那總是很好。 對於生產代碼,您應該更喜歡使用現有的內置庫方法。

    int rounded = Math.toIntExact(Math.round(-23.6));
    System.out.println("Rounded: " + rounded);

取整:-24

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM