Java 如何消除返回高值的错误?
基本上,我试图使double与整数一起工作,也许我遗漏了一些明显的东西,但是,对于返回高值代码,我得到一个错误,上面说,“可能会丢失精度,必需:int,找到:double”。就评论而言,这是我正在上的一门课。代码如下:Java 如何消除返回高值的错误?,java,arrays,integer,double,max,Java,Arrays,Integer,Double,Max,基本上,我试图使double与整数一起工作,也许我遗漏了一些明显的东西,但是,对于返回高值代码,我得到一个错误,上面说,“可能会丢失精度,必需:int,找到:double”。就评论而言,这是我正在上的一门课。代码如下: package pj701; public class PJ70103 { public static void main(String[] args) { //DO NOT CHANGE ANYTHING IN THE MAIN() d
package pj701;
public class PJ70103 {
public static void main(String[] args)
{ //DO NOT CHANGE ANYTHING IN THE MAIN()
double[] x = { 11.11, 66.66, 88.88, 33.33, 55.55 };
double[] y = { 9, 6, 5, 8, 3, 4, 7, 4, 6, 3, 8, 5, 7, 2 };
double[] z = { 123, 400, 765, 102, 345, 678, 234, 789 };
int index = FindIndexHighest (x);
System.out.printf( "%s%5d%s%8.2f\n", "Array x: element index = " , index,
" element contents = ", x[index] );
index = FindIndexHighest (y);
System.out.printf( "%s%5d%s%8.2f\n", "Array y: element index = " , index,
" element contents = ", y[index] );
System.out.printf( "%s%5d%s%8.2f\n", "Array z: element index = ",
FindIndexHighest (z), " element contents = ",
z[FindIndexHighest (z) ] );
}
//======================================================
// put your method definition here - - ONE method
//======================================================
public static int FindIndexHighest(double[] x)
{
double highValue = 0;
for (int i = 1; i < x.length; i++)
{
if (x[i] > highValue)
{
highValue = x[i];
}
else
{
highValue = highValue + 0;
}
}
return highValue;
}
}
包装pj701;
公共类PJ70103{
公共静态void main(字符串[]args)
{//不要更改MAIN()中的任何内容
双[]x={11.11,66.66,88.88,33.33,55};
双[]y={9,6,5,8,3,4,7,4,6,3,8,5,7,2};
双[]z={123400765102345678234789};
int index=FindIndexHighest(x);
System.out.printf(“%s%5d%s%8.2f\n”,“数组x:element index=”,index,
“元素内容=”,x[索引];
索引=FindIndex(y);
System.out.printf(“%s%5d%s%8.2f\n”,“数组y:element index=”,index,
“元素内容=”,y[索引];
System.out.printf(“%s%5d%s%8.2f\n”,“数组z:element index=”,
FindIndexHighest(z),“元素内容=”,
z[FindIndexHighest(z)];
}
//======================================================
//把你的方法定义放在这里--一个方法
//======================================================
公共静态int FindIndexHighest(双精度[]x)
{
双高值=0;
对于(int i=1;i高值)
{
高值=x[i];
}
其他的
{
高值=高值+0;
}
}
返回高值;
}
}
您得到错误是因为您错误地实现了该方法。返回的是最高值(双精度),而不是最高索引(整数)。您需要返回具有最高值的元素的索引
您还应该知道数组的第一个索引是索引0,而不是索引1。我认为您需要再次检查分配的要求。请求的不是值,而是传递数组中该值的索引 至于编译器警告,这意味着当您试图隐式地将double转换为int时,可能会丢失一些已有的信息。例如,
double d=3.5;int i=d
将导致i==3
,因此小数点后的信息丢失。这就是编译器警告您的。要消除警告,请发出显式强制转换,例如inti=(int)d在上面的示例中,代码>