[英]Rounding Issue with Quadratic Program
在我正在練習的問題中,目標是編寫二次表達式,然后將其舍入到千位。 這是所需的輸出:
1(a變量)6(b變量)3(c變量)
4(a變量)10(b變量)6.1(c變量)
輸出:-0.551,-5.449(頂部答案)
-1.056,-1.444(底線答案)
問題不在於如何解決問題,而是我所得到的答案。 如下計算二次方程式時:
double a = scan.nextDouble();
double b = scan.nextDouble();
double c = scan.nextDouble();
//equation is correct
double answer1 = 0.001 * Math.floor((-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a)* 1000.0) ;
double answer2 = 0.001 * Math.floor((-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a) * 1000.0);
我得到的答案是正確的,除了當我將四舍五入到千分之一的位置時,一些數字是正確的,而其他數字卻不是,即使看起來它們是正確地四舍五入,只是沒有根據問題而定。
我的輸出:-0.551,-5.45 -1.057,-1.444
這與我四舍五入有關嗎? 任何理解此舍入問題的幫助將不勝感激:)
https://floating-point-gui.de/languages/java/
如何取整
獲取字符串:
String.format("%.2f", 1.2399) // returns "1.24"
String.format("%.3f", 1.2399) // returns "1.240"
String.format("%.2f", 1.2) // returns "1.20"
要打印到標准輸出(或任何PrintStream):
System.out.printf("%.2f", 1.2399) // same syntax as String.format()
如果不想尾隨零:
new DecimalFormat("0.00").format(1.2)// returns "1.20"
new DecimalFormat("0.##").format(1.2)// returns "1.2"
如果需要特定的舍入模式:
new BigDecimal("1.25").setScale(1, RoundingMode.HALF_EVEN); // returns 1.2
如果確實需要舍入實際數字,而不僅僅是打印輸出:
double result = Math.round(value * scale) / scale;
其中, scale
可能被固定在1000
三個小數位或小數點后任意數量的計算:
int scale = (int) Math.pow(10, precision);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.