我试图在数组中找到高低数字,但我不确定为什么我的代码无法正常工作.它给了我0和56的输出.我理解为什么它给0,但56来自哪里?
package test;
public class Test {
public static void main(String[] args) {
int[] numbs = { '2', '4', '2', '8', '4', '2', '5'};
int count = 0;
int low = 0;
int high = 0;
while(count < numbs.length)
{
if(numbs[count]< low) {
low = numbs[count];
}
if(numbs[count]> high) {
high = numbs[count];
}
count++;
}
System.out.println(low);
System.out.println(high);
}
}
Run Code Online (Sandbox Code Playgroud)
你需要开始low足够低; 目前,你从零开始 - 太低而不能"捕获"数组的最低元素.
有两种方法可以解决这个问题:
Integer.MAX_VALUE和Integer.MIN_VALUE启动high和low,或high和low,则过程开始与所述第二元件的阵列.int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;
Run Code Online (Sandbox Code Playgroud)
PS你会发现打印出奇怪的数字,因为你使用的是字符而不是整数:
int[] numbs = { 2, 4, 2, 8, 4, 2, 5};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6864 次 |
| 最近记录: |