簡體   English   中英

為什么我的格式這么奇怪?

[英]Why is my formatting so strange?

我的代碼格式有問題。 最后,它應該打印出它的結果。 我正在使用 printf 語句,但它返回的數字沒有我需要的那么精確。 例如,如果一個數字應該是 76.83200000000001,它會返回 76.83200。 它還在數字末尾添加了不必要的零,如果一個數字應該是 28.0,它就會變成 28.000000。 如果可能,我們可以在沒有BigDecimal變量的情況下做到這一點嗎? 到目前為止,這是我的代碼(注意:某些字符串前面有空格,這是因為我提交的網站出於某種原因需要這樣做):

import java.util.Scanner;
public class Population {
    public static void main(String[] args) {
        Scanner stdin = new Scanner(System.in);
        double startingNumber, dailyIncrease, daysWillMultiply, temp, population;

        System.out.print("Enter the starting number organisms: ");
        startingNumber = stdin.nextDouble();
        while(startingNumber < 2) {
            System.out.print("Invalid. Must be at least 2. Re-enter: ");
            startingNumber = stdin.nextDouble();
        }

        System.out.print("Enter the daily increase: ");
        dailyIncrease = stdin.nextDouble();
        while(dailyIncrease < 0) {
            System.out.print("Invalid. Enter a non-negative number: ");
            dailyIncrease = stdin.nextDouble();
        }

        System.out.print("Enter the number of days the organisms will multiply: ");
        daysWillMultiply = stdin.nextDouble();
        while(daysWillMultiply < 1) {
            System.out.print("Invalid. Enter 1 or more: ");
            daysWillMultiply = stdin.nextDouble();
        }


        temp = startingNumber * dailyIncrease;
        population = startingNumber;

        System.out.println("Day\t\tOrganisms");
        System.out.println("-----------------------------");
        System.out.println("1\t\t" + startingNumber);
        for (int x = 2; x <= daysWillMultiply; x++) {
            population += temp;
            temp = population * dailyIncrease;
            System.out.printf(x + "\t\t%f\n", population);
        }
    }
}

好吧,我刪除了我之前的答案,因為它完全錯誤(感謝@JohnKugelman 指出這一點)。 我認為由於轉換為float會丟失精度,但事實並非如此。

根據格式化程序文檔,使用%f標志時會發生以下情況:

  • 幅度m (參數的絕對值)被格式化為m的整數部分,沒有前導零,后跟小數分隔符,后跟一個或多個代表m的小數部分的十進制數字。

  • 結果中m的小數部分的位數等於精度。 如果未指定精度,則默認值為 6

  • 如果精度小於分別由Float.toString(float)Double.toString(double)返回的字符串中小數點后出現的位數,則該值將使用四舍五入算法進行四舍五入。 否則,可能會附加零以達到精度。

這就是為什么你會得到不必要的零和削減數字。

文檔建議使用Float.toString(float)Double.toString(double)作為值的規范表示。

如果你想使用System.out.printf(...); ,你可以用%s替換你的%f標志 - 在這種情況下,參數將被轉換為一個字符串(結果是通過調用參數的toString()方法獲得的,這就是你需要的)。 例如,您可以重寫這一行:

System.out.printf(x + "\t\t%f\n", population); 

如下:

System.out.printf("%d\t\t%s\n", x, population);

這將打印您的population的確切值。

檢查此線程的第一個答案,它可能會有所幫助。

java中有多少有效數字有浮點數和雙精度數?

重要的是要了解精度不是統一的,並且這不是像整數那樣精確存儲數字。

暫無
暫無

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

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