簡體   English   中英

整數數組和雙數組 - 區別

[英]int array and double array - difference

下面代碼中的int數組和新的double數組有什么區別?

public class TestTwoReview {
    public static void main(String[] args) {
        int ducky[] = { 21, 16, 86, 21, 3 };
        int sum = 0;

        for (int counter = 0; counter <ducky.length; counter++) {
            // adding all numbers in array
            sum += ducky[counter];
        }

        System.out.println("the sum of array is " + sum);

        double[] scores = new double[10];
        double total = 0;
        double average;

        for (int index = 0; index < scores.length; index++)
            total += scores[index];

        average = total / scores.length;
        System.out.println("the average is " + average);
    }
}

您的代碼看起來並不像在做一些有用的事情。 也許這才是最讓你困惑的。 尤其是第二部分基本上什么都不做。


分析

讓我們仔細看看它。 int數組ducky包含一些數據。 你迭代它的所有元素並總結它們 因此sum正確地包含了所有條目的累計值,我猜應該是147

第二部分初始化一個double精度數組,其中包含10元素。

double[] scores = new double[10];

由於double原始數據類型,因此數組將在每個條目處預先填充0.0

scores[0] => 0.0
scores[1] => 0.0
scores[2] => 0.0
...
scores[9] => 0.0

接下來,您類似地迭代所有這些條目並將它們總結在變量total

total += scores[index];

但是,由於每個條目的scores[index]0.0 ,因此總和也將為0.0 接下來計算平均值

average = total / scores.length;

如果我們輸入值,我們有

average = 0.0 / 10
        = 0.0

所以average也是0.0

總而言之第二部分錯過了一些有意義的數據,否則它會首先計算總和和旁邊也平均值。


區別

但是,如果我們甚至假設scores會填充一些有意義的數據,又有什么區別呢?

好吧,唯一的區別是它還允許十進制值,僅此而已。

例如,您可以像這樣創建它

double[] scores = { 1.7, 2.3, 6.12, 9.1, 2.0 };

總和total那么將是21.22 ,平均為2.122

int數組不能這樣做,它只接受非十進制值(整數)。

暫無
暫無

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

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