gpt4 book ai didi

java - 数组 - 数组的平方根并打印结果 JAVA

转载 作者:行者123 更新时间:2023-12-01 07:42:11 24 4
gpt4 key购买 nike

我试图获得一组(9)数字的平方根然后打印,但我总是返回只有一个结果 - 数组中数字的平方 - 显然不是我想要的。谢谢你的帮助。好吧,这是到目前为止我的糟糕代码。也尝试将其传递给方法。

public static void main ( String args[] )
{
double[] nums = {126, 12.939, 795, 320.16,
110, 34.7676, 7773, 67, 567, 323};

System.out.println ("Square root is " +square);
square(nums);
}

public static double square (double [] array) {
double result;
for( double i = 0; i < array.length ; i++ )
result = Math.sqrt(array[i]);

return result;
}
}

最佳答案

您只有一个变量result来存储平方根,因此它会被覆盖,最终它只包含最新的平方根。如果您想要数组中每个元素的平方根,则还需要将结果存储在数组中,例如

public static double[] square (double [] array) {
double[] result = new double[array.length];
for(int i = 0; i < array.length ; i++ )
result[i] = Math.sqrt(array[i]);

return result;
}

然后就可以将结果一一打印出来,例如:像这样:

public static void main ( String args[] )
{
double[] nums = {126, 12.939, 795, 320.16,
110, 34.7676, 7773, 67, 567, 323};
double[] squares = square(nums);

for(int i = 0; i < nums.length ; i++ )
System.out.println ("Square root of " + nums[i] + " is " + squares[i]);
}

更新:并且我的机器上的结果如预期的那样:

Square root of 126.0 is 11.224972160321824
Square root of 12.939 is 3.597082150855051
Square root of 795.0 is 28.19574435974337
Square root of 320.16 is 17.893015397076034
Square root of 110.0 is 10.488088481701515
Square root of 34.7676 is 5.896405684821898
Square root of 7773.0 is 88.16461875378354
Square root of 67.0 is 8.18535277187245
Square root of 567.0 is 23.811761799581316
Square root of 323.0 is 17.97220075561143

关于java - 数组 - 数组的平方根并打印结果 JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2945613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com