我有一个关于如何使用数组执行计算的问题。在我的例子中,我需要执行数组的计算,然后在main方法中调用它。我在返回类型中进行了计算,并且编译器抱怨double不能转换为double []所以我尝试获取数组的长度,但仍然得到相同的警告。我怎样才能解决这个问题?任何帮助将不胜感激。以下是我的代码:
// calcGravity returns an array of doubles containing teh gravity values
//and takes two arrays of doubles as parameters for the radius values and mass
public static double[] calcGravity(double[] radius, double[] mass)
{
// fill in code here
return (6.67E-17) * mass.length / Math.pow(radius.length, 2);
// The formula to calculate gravity is:
// 6.67E-17 times the massOfPlanet divided by the radius of the planet squared
}
答案 0 :(得分:1)
public static double[] calcGravity(double[] radius, double[] mass)
{
double[] ret = new double[radius.length];
for (int i=0;i<radius.length;i++) {
// fill in code here
ret[i] = (6.67E-17) * mass[i] / Math.pow(radius[i], 2);
// The formula to calculate gravity is:
// 6.67E-17 times the massOfPlanet divided by the radius of the planet squared
}
return ret;
}
答案 1 :(得分:0)
您需要分别对每一行进行计算。
double[] gravities = new double[radius.length]();
for (int i =0; i<radius.length;i++) {
gravities[i] = (6.67E-17) * mass[i] / Math.pow(radius[i], 2);
}
return gravities;
答案 2 :(得分:0)
double[]
是一系列双打。你只是计算一个数字。当您尝试返回double
并且返回类型为double[]
时,编译器无法转换它。
你的计算错了。 radius
和mass
的长度不是半径和质量。它们每个都包含一串数字,每个数字都是半径和质量。您想要计算每个质量/半径对的每个重力并返回包含以下内容的新数组:
public static double[] calcGravity(double[] radius, double[] mass)
{
// Check that you have the same number of radii as masses
if (radius.length != mass.length)
throw new IllegalArgumentException("Cannot calculate gravities with unequal radii and masses.");
double[] gravity = new double[radius.length];
for (int i = 0; i < radius.length; i++) {
double[i] = (6.67E-17) * mass[i] / Math.pow(radius[i], 2);
}
return gravity;
}
答案 3 :(得分:0)
如果您正在访问mass.length
和radius.length
,您将获得这些数组中的元素数量。
所以你必须编写一个循环来迭代这些数组中的所有值。
public static double[] calcGravity(double[] radius, double[] mass) {
int size = radius.length;
if (size != mass.length) {
throw IllegalArgumentException("can't calculate with different count of array elements!");
}
double[] sums = new double[size];
for (int i = 0; i < size; i++) {
sums[i] = (6.67E-17) * mass[i] / Math.pow(radius[i], 2);
}
return sums;
}
答案 4 :(得分:0)
public static double[] calcGravity(double[] radius, double[] mass){
double[] grav = new double[radius.length]();
for (int i =0; i<radius.length;i++) {
grav[i] = (6.67E-17) * mass[i] / Math.pow(radius[i], 2);
}
return grav;
}