0

我必须制作一个程序,告诉你 5 个数字中的最大和最小数量,并且输出时我不断得到最小 = 0 和最大 = 0。我还没有添加评论或类似的东西,我尝试了 else if 并且它根本没有工作(很惊讶我得到了 else 工作)。有人可以帮我解决这个问题。我不应该需要帮助,但我就是想不通。

public class int_big_small {
    public static void main(String args[]){

        int num1=3, num2=9, num3=5, num4 = 3, num5 = 7;
        int largest = 0, smallest = 0;

            if(num1 > num2){
                num1 = largest;
                num2 =  smallest;
            }else{
                num2 = largest;
                num1 = smallest;
            }

            if(num3>largest){
                num3 = largest;
            }
            if(num3<smallest)
                num3 = smallest;
            if(num4>largest){
                num4 = largest;
            }
            if(num4<smallest)
                num4 = smallest;

            if(num5>largest){
                    num5 = largest;
                }
                if(num5<smallest)
                    num5 = smallest;



            System.out.println("the smallest number is " + smallest + " and the largest is " + largest);
    }
}
4

3 回答 3

2

Your assignments are all in reverse order - they should be smallest = whatever, not whatever = smallest

This is also crying out to be put in for loop.

int[] nums = new int[] {num1, num2, num3, num4, num5};
int smallest = nums[0];
int largest = nums[0];
for(int i = 1; i < nums.length; i++) {
    if(nums[i] < smallest) {
        smallest = nums[i];
    }
    if(nums[i] > largest) {
        largest = nums[i];
    }
}

Initialize smallest and largest to a valid int from your list of numbers - initializing them to 0 is going to result in smallest equaling 0 when you're finished. (The only default values that wouldn't cause problems are smallest = Integer.MAX_VALUE; largest = Integer.MIN_VALUE;)

于 2013-04-12T16:23:12.767 回答
1
public int min(int a, int b) {
    if(a > b) return b;
    return a;
}

public int max(int a, int b) {
    if(a > b) return a;
    return b;
}

int num1=3, num2=9, num3=5, num4 = 3, num5 = 7;
int largest = num1, smallest = num1;

smallest = min(min( min(num1, num2) , min(num3, num4)), num5);
largest  = max(max( max(num1, num2) , max(num3, num4)), num5);
于 2013-04-12T16:28:00.270 回答
1

如果您正在学习Java,请使用带有数组和循环的解决方案。如果您使用的是Java,则可以分 3 行完成:

List<Integer> list = Arrays.asList(num1, num2, num3, num4, num5);
int smallest = Collections.min(list);
int largest  = Collections.max(list);
于 2013-04-12T16:46:53.870 回答