2015-10-16 98 views
-2

所以我已经寻找不同的方法,他们都显得办法复杂。那么到底需要做什么,为了打印数组,我宁愿不使用数组util?到目前为止,我有这样的:爪哇 - 打印阵列

public static void main(String[] args) 
{ 
    int a[] = {2, 3, 5, 7, 11, 13}; 

    int sum = 0; 

    System.out.printf("The average of \n" + a); 

    for(int i = 0; i < a.length; i++) 
     sum = sum + a[i]; 

    double avg = sum/a.length; 

    System.out.println("\nis\n " + avg); 
} 

而且它打印此:

The average of
[[email protected] is 6.0

我是这样假设(不知道我是正确的)意味着它打印阵列的位置不是被包含。 (如果我错了,请纠正我)同样,我们得到的答案是6.83,我的读数是6.0,这意味着我做错了什么。关于如何在不使用任何特殊库的情况下打印数组以及数学问题来自哪里的任何想法?

+4

见http://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array和http: //stackoverflow.com/questions/19620225/why-double-width-50-110000-the-output-is-0-000000000000000/19620230 –

+1

的System.out.println(Arrays.toString的(a)); – Siddhartha

+1

尽管如此,你不应该抵制'Arrays#toString'。它*非常棒*且比其他任何东西都更具可读性。 – Makoto

回答

0
System.out.printf("The average of \n" + a); 

您正在打印数组对象,您应该遍历它并单独打印内容。您可以使用打印数组的内容。同时施加其中一个值(sumarray length)到double得到平均值。珍贵。使用System.out.format()打印十进制值。

int a[] = {2, 3, 5, 7, 11, 13}; 
System.out.print("The average of \n" + Arrays.toString(a)); // print the array 

for(int i = 0; i < a.length; i++) 
    sum = sum + a[i]; 

double avg = (double)sum/a.length; // cast one of the value to double 

System.out.format(" is %.2f", avg); // print the output upto two decimal. 

输出:

The average of 
[2, 3, 5, 7, 11, 13] is 6.83 
+0

为什么投了票,请评论? – YoungHobbit

+0

我不确定。我积极寻求帮助。所以就我而言,谢谢! :D – NaughtyBear

+1

我会的时候会允许我。 “发布后5分钟内不能接受答案”。 – NaughtyBear