找到第二个最小整数时输出不正确

用户名

以下代码仅偶尔返回正确的值,无论是否正确,似乎完全是随机的。指针好吗?

/*This program takes a series of integers as user input
 * and returns the second smallest amongst them to the
 * console. 
 * 
 * For reasons unknown to the programmer, ending user 
 * input with Ctrl-D only works occasionally. If Ctrl-D
 * fails, enter any character(s) to the console and press 
 * enter. Make sure the dummy characters are separated 
 * from any integers with whitespace. The program should 
 * execute normally, ignoring the dummy character(s).
 * 
 * Written by xxxxxx, w45-2013*/

package secondSmallest;

import java.io.PrintStream;
import java.util.Scanner;

public class SecondSmallest {

    PrintStream out;
    Scanner in;

    SecondSmallest() {
        out = new PrintStream(System.out);
        in = new Scanner(System.in);
    }

    void start() {
        out.printf("Enter 3 or more positive integers, seperate with whitespace. End input with Ctrl-D.%nInteger input:");
        int smallest, secondSmallest = 2147483647, nextInt;
        smallest = in.nextInt();
        while (in.hasNextInt()) {
            nextInt = in.nextInt();
            if (nextInt < smallest) {
                secondSmallest = smallest;
                smallest = nextInt;
            }
        }
        out.printf("The second smallest integer is %d", secondSmallest);
    }

    public static void main(String[] args) {
        new SecondSmallest().start();
    }
}
Zong

当只需要更新第二个最小的数字时,您可能就错过了第二种情况:

if (nextInt < smallest) {
    secondSmallest = smallest;
    smallest = nextInt;
} else if (nextInt < secondSmallest) {
    secondSmallest = nextInt;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

htonl / ntohl在第二个命令上的值不正确?

来自分类Dev

htonl / ntohl在第二个命令上的值不正确?

来自分类Dev

查找数组中的第二个最小整数

来自分类Dev

GetMonitorInfo和GetDeviceCaps中第二个监视器的宽度和高度不正确

来自分类Dev

为什么 long 在查找三个整数的第二个最大值时显示错误的输出?

来自分类Dev

Java二进制搜索树找到第二个最小的节点

来自分类Dev

在数据框中找到第二个最小值的索引

来自分类Dev

DAX公式以其他条件找到第二个最小值

来自分类Dev

寻找最小和第二个最小的数字

来自分类Dev

汇编代码返回数组中的最小整数,而不是随机返回倒数第二个或倒数第二个

来自分类Dev

查询以拉第二个最小的id

来自分类Dev

寻找第二个最小值

来自分类Dev

寻找第二个最小值

来自分类Dev

基于标准的第二个最小值

来自分类Dev

如何找到倒数第二个符号?

来自分类Dev

删除在第二个文件中找到的单词

来自分类Dev

如何找到同名的第二个div类?

来自分类Dev

根据对的第二个值找到对的向量的上限

来自分类Dev

标签子集到第二个输出

来自分类Dev

从第二个开始复制输出

来自分类Dev

获取倒数第二个值并输出

来自分类Dev

在创建第二个线程时遇到麻烦

来自分类Dev

激活第二个网卡时无法ping

来自分类Dev

添加第二个RSU时交换消息

来自分类Dev

打开第二个OdbcConnection时断言失败

来自分类Dev

激活第二个网卡时无法ping

来自分类Dev

存储套件在第二个请求时崩溃

来自分类Dev

打开第二个文档时Word冻结

来自分类Dev

MPMoviePlayerController在第二个X时自动暂停