[英]Find lowest odd number in a loop
I know this code is wrong. 我知道这段代码是错误的。 I'm a beginner so bear with me.
我是一个初学者,请多多包涵。
I need to find the lowest odd number but it keeps coming up as zero no matter what numbers are entered. 我需要找到最低的奇数,但无论输入什么数字,它都会一直为零。 I need to initialize 'lowest' but how/where do I initialize it?
我需要初始化“最低”,但如何/在哪里初始化呢?
lowest = 0 is causing a problem but I'm not sure where to initialize lowest 最低= 0引起问题,但我不确定在哪里初始化最低
class Odd
{
public static void main(String[] args)
{
int number; //the number entered by the user
int input; //the amount of numbers to be entered by the user
int index;
int lowest = 0; //lowest odd number
System.out.println("How many numbers? ");
input = EasyIn.getInt();
for (index = 1; index <= input ; index ++)
{
System.out.println("Enter number " + index + ":" );
number = EasyIn.getInt();
if ((number % 2 == 1) && (number < lowest))
{
lowest = number;
}
}
System.out.println("The lowest odd number entered was " + lowest);
}
}
If you're sure your input isn't empty, a solution is to initialize lowest
to a big enough value : 如果您确定输入不为空,则一种解决方案是将
lowest
值初始化为足够大的值 :
int lowest = Integer.MAX_VALUE;
This ways all values will be smaller, so lowest
will be one of the values of your input. 这样,所有值都将变小,因此
lowest
值将是您输入的值之一。
You are starting at 0
so you will not get a value larger. 您从
0
开始,所以不会得到更大的值。 If you start like this 如果你这样开始
int lowest = Integer.MAX_VALUE;
Also (n % 2) will only be 1 for positive numbers. 同样(n%2)对于正数将仅为1。 If you want to test for odd negative numbers you want
(n & 1) != 0
如果要测试奇数负数,则需要
(n & 1) != 0
Note: Integer.MAX_VALUE is an odd number so even if this is the only value it will be the maximum. 注意:Integer.MAX_VALUE是一个奇数,因此即使这是唯一的值,也将是最大值。 However, if you want to be able to tell the difference between some one entering this value and no odd values you can use this instead.
但是,如果您希望分辨输入该值的某人与没有输入奇数的人之间的区别,可以改用此方法。
long lowest = Long.MAX_VALUE;
This will allow you to tell the difference between Integer.MAX_VALUE being entered and no value as Long.MAX_VALUE is much higher. 这将使您分辨输入的Integer.MAX_VALUE与无值之间的区别,因为Long.MAX_VALUE更高。
You initialise lowest as 0 and then look for numbers lower than it (and odd). 您将最低初始化为0,然后寻找比它低(且为奇数)的数字。
I'd initialise it as EasyIn.getInt() so it's the first number in your list to check through. 我将其初始化为EasyIn.getInt(),因此它是您列表中第一个要检查的数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.