-4

好的,我找到了 2 个有效的短代码,但我想了解它们是如何工作的。我已经用谷歌搜索并检查了以下链接:

http://www.tutorialspoint.com/java/lang/math_pow.htm http://www.tutorialspoint.com/java/lang/math_sqrt.htm

但那里的解释不清楚。所以换句话说,我希望知道/理解这两个代码的每一行发生了什么。

A)下面的程序片段计算(给定一个整数数组数据)并打印数据中所有条目的几何平均值:

   double product = 1;// For example, I understand why it is 1, since if it was 0 then the product would be keep getting 0, since any number *0 is always zero.
    for(int i=0; i<data.length; i++)//okay for loop is getting out all the intergers from the data array.
    product*=data[i];//This is I am not too sure, I guess each item in array is getting multiplied with each other????
    double gmean=Math.pow(product,1.0/data.length); // Yes, I hate this line, because I don't understand it, can someone explain this line please? Please use easy English, I am not as smart as you.

B)第二个代码片段计算(给定一个整数数组数据)并打印数据中所有条目的二次平均值:

double sum=0; //Okay the sum should be 0 because at the moment nothing has been summed up.
for(int i=0; i<data.length; i++)// Now getting out all the items in array called data.
sum+= data[i]*data[i];//Now I am not too sure, all the items in the array called data is getting multiplied with each other and then getting added up? I am not too sure, if would be good if someone could explain this with easy English.
double qmean = Math.sqrt(sum/data.length);// I hate this line, because I don't understand it.
System.out.println(qmean);// Displays the final result.

好的,正如你所看到的,我确实理解了代码中的一些行,虽然有些行,我不明白,如果有人能解释这些行,那就太棒了,我不太理解使用简单的英语而不是以一种复杂的方式。

提前致谢。

4

2 回答 2

1

假设数据是 {3,2,7}。data.length 为 3。这将计算 sqrt((9+4+49)/3)。

double sum=0;
// sum is now zero

for(int i=0; i<data.length; i++)
// Execute the following statement with i having each value starting from 0,
// incrementing by 1 each time (i++), as long as i remains less than 3.
    sum+= data[i]*data[i];
    // The sum+= statement is executed three times, with i each of 0, 1, and 2.
    // The first time adds 9 to sum getting 9
    // The second time adds 4 to sum getting 13
    // The third time adds 49 to sum, getting 62

double qmean = Math.sqrt(sum/data.length);
// make qmean equal to sqrt(62/3).

System.out.println(qmean);// Displays the final result.
于 2014-05-01T20:57:43.103 回答
0

math.pow(a,b) 表示 a^b 而 math.sqrt(a) 是 a 的平方根。您不了解内容中的java方法或数学逻辑?

于 2014-05-01T20:25:50.470 回答