寻找最小和第二个最小的数字 [英] finding smallest and second smallest number

查看:63
本文介绍了寻找最小和第二个最小的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该程序应该在x个数字中找到最小的和第二个最小的数字. 该程序每次都会找到最小的数字,但是我在替换键盘上的第二个最小数字时遇到问题.

This program is supposed to find the smallest and the second smallest number among x numbers. The program finds the smallest number every time, but I have problems replacing the second smallest number from the keyboard.

 System.out.println("How many numbers?");
 int total = keyboard.nextInt();

 System.out.println("What is the first number");
 int small = keyboard.nextInt();

 System.out.println("whats the second number");
 int nest = keyboard.nextInt();
 // Assigning the first two numbers to smallest and second largest

 for (int i =2;i<total;i++) {                     
    System.out.println("whats the next number?");
    int number = keyboard.nextInt();

    if (number < small) {
       small = number;
    } // this part works (I think)

    if ((number > small) && (number < nest)) {
       nest = number;
    }//this part dont (I think)

 }//end forloop
 System.out.printf("The smallest numbers are %d and %d",small,nest); 

推荐答案

您只需要正确订购即可.首先,查看该数字是否小于最小数字,如果是,则将其替换并将旧的最小数字移至第二个最小数字.否则,如果它小于第二个最小的数字,则将其替换.

You just have to get the order right. First, see if the number is smaller than the smallest number, and if so, replace it and move the old smallest number to the second smallest number. Else, if it is smaller than the second smallest number, replace that.

这是应该在循环中的代码:

Here's the code that should be in the loop:

if (number < small) {
    nest = small;
    small = number;
} else if (number < nest) {
    nest = number;
} 

这篇关于寻找最小和第二个最小的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆