程序計算五個數字的平均值

[英]Program to calculate average of five numbers


I am a beginner in java and wrote a program to calculate the average of five numbers. But i don't know why it came up with an error. So what can I do to resolve this.

我是java的初學者,寫了一個程序來計算五個數字的平均值。但我不知道為什么會出現錯誤。那么我該怎么做才能解決這個問題。

public static void main(String args[]){
  int nums[]=new int[5];
  nums[]={1,3,5,7,9};       
  int num2=0,i;
  for(i=0;i<=4;i++){
    num2=nums[i]+num2;
  }
  System.out.println(num2/5);
}

Thanks

1 个解决方案

#1


3  

You can't assign a value to an array using initializer notation you after have declared it. (The hint is in the name - you can only use it to initialize the array).

在聲明它之后,您無法使用初始化符號為數組賦值。 (提示在名稱中 - 您只能使用它來初始化數組)。

Instead of

int nums[]=new int[5];
nums[]={1,3,5,7,9};

use

int nums[] = {1,3,5,7,9};

You can use:

您可以使用:

nums = new int[] {1,3,5,7,9};

but you don't need to assign a value to the array first using int nums[] = new int[5]; - int nums[]; is sufficient.

但是你不需要首先使用int nums [] = new int [5]為數組賦值; - int nums [];足夠了。


Also, it is generally considered better to use int[] nums instead of int nums[]: the "array-ness" is part of the type, not the variable name, so keep the [] with the int.

另外,通常認為使用int [] nums而不是int nums []更好:“array-ness”是類型的一部分,而不是變量名,所以將[]與int保持一致。

(The int nums[] form was included in early versions of Java to make the language more familiar to C/C++ programmers, and we're now stuck with it.)

(int nums []表單包含在Java的早期版本中,以使C / C ++程序員更熟悉該語言,現在我們已經堅持使用它了。)


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/09/30/eec7d30ffc7fb8f86e029e65e8d2cedb.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com