【发布时间】:2015-10-01 06:48:35
【问题描述】:
在这段代码中,-20 应该是最小值,因为它的负数和离零最远的值对吗?但是当我运行 MinAlgoritm 时,会打印出整数 5。我有一个可以正常工作的 Max 版本,但事实并非如此。怎么会这样?有什么我可以做的改进吗?
class MinAlgorithm
{
public static void main ( String[] args )
{
int[] array = { -20, 19, 1, 5, -1, 27, 19, 5 } ;
int min;
// initialize the current minimum
min = array[0];
// scan the array
for ( int index=0; index < array.length; index++ )
{
if (array[index]<min);
min=array[index];
}
// Print out the result
System.out.println("The minimum of this array is: " + min );
}
}
【问题讨论】:
-
您认为
if (array[index]<min);有什么作用,为什么? (注意悬空的;。) -
@Andy 它会导致empty statement。
标签: java algorithm max min negative-number