我目前正在为我的高中计算机科学课做作业,我遇到了一个问题,我收到错误“double[] cannot be converted to double”。但是,我很困惑,因为我告诉一个特定的方法返回一个 double 组。
public static double [] getHits(int attempts) {
Random ranInt = new Random();
int range = ranInt.nextInt(2) - 1;
double hits = 0;
double [] hitsInTrial = new double[attempts];
double radius = 1;
double x = Math.pow( range, 2);
double y = Math.pow( range, 2);
for( int index = 0; index < attempts; index++)
{
if( !(x + y <= radius) )
{
hits++;
}
hitsInTrial[index] = hits;
}
return hitsInTrial;
}
^此方法应该返回 hitsInTrial 的双数组(我觉得好像某些数据有误,但我会在解决问题后担心)。
public static void main()
{
Scanner in = new Scanner(System.in);
System.out.print("How many darts/trials?: ");
int dartThrows = in.nextInt();
double[] trials = new double[10];
double[] hits = new double[dartThrows];
for( int index = 0; index < trials.length; index++)
{
hits[index] = getHits( dartThrows );
}
}
我在 hit[index] = getsHits( dartThrows ) 中收到错误;区域。我很困惑,因为 getHits 方法被告知返回一个 double 组,但我收到“无法转换”错误。任何帮助将不胜感激,因为作为新手,我不太确定哪里出了问题。
我省略了两种方法,一种是使用数据计算圆周率,另一种是打印结果。这些方法不会产生错误,但如果我需要提供它们来帮助回答,请告诉我。
最佳答案
您的 getHits()
方法返回 double 组:double[]
。而您的 hits[]
数组是 double[]
类型,因此它的元素是 double
类型。您尝试为其分配 double[]
返回值。
关于java - 无法将 double 组转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28463774/