簡體   English   中英

矩陣加法結果怪異

[英]Matrices addition with weird result

我寫了下面的代碼...

public class MatrixAddition
{
    public static void main(String[] args)
    {

        double matrix[][] = { { 1.2, 3.3, 1.2 }, { 1.0, 2.2, 4.5 }, { 1.3, 4.5, 2.2 } };
        double matrix1[][] = { { 2.2, -3.3, 1.1 }, { 7.0, -2.2, 4.2 }, { 2.2, 0.0, 0.3 } };
        double result[][] = new double[matrix.length][matrix1.length];

        for(int iResult = 0; iResult < result.length; iResult++) {
            for(int jResult = 0; jResult < result[iResult].length; jResult++) {
                result[iResult][jResult] = matrix[iResult][jResult] + matrix1[iResult][jResult];

                System.out.print(result[iResult][jResult] + " ");
            }

            System.out.print("\n");
        }
    }
}

結果是:

3.4000000000000004 0.0 2.3

8.0 0.0 8.7 

3.5 4.5 2.5 

每當我更改Matrix [i0] [j0]和Matrix1 [i0] [j0]的值時,我都會得到正確的結果,但是當值分別為1.2和2.2時,我總會得到3.400000000000004。 我該如何解決,以及為什么會發生。

提前致謝。

浮點值是近似值。 一些十進制值不能由它們精確表示。 通常,您可以通過在輸出數字時將數字格式設置為合理的小數位數來隱藏它們。 或使用其他數字類型,例如BigDecimal

正如其他人所說, 這是由於使用了浮點值而發生的- 這是一個很棒的問題,其中包含對此問題的解釋

暫無
暫無

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

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