【问题标题】:smallest and largest of the inputs最小和最大的输入
【发布时间】:2013-02-26 01:13:01
【问题描述】:

我被分配编写一个程序,该程序读取一系列整数输入并打印 - 最小和最大的输入 - 以及偶数和奇数输入的数量

我想出了第一部分,但对如何让我的程序显示最大和最小感到困惑。到目前为止,这是我的代码。我怎样才能让它也显示最小的输入?

public static void main(String args[])
{
      Scanner a = new Scanner (System.in);
      System.out.println("Enter inputs (This program calculates the largest input):");

      double largest = a.nextDouble();
      while (a.hasNextDouble())
      { 
          double input = a.nextDouble();
          if (input > largest)
          {
              largest = input;
          }
      }


      System.out.println(largest);
}

【问题讨论】:

  • 您只需要两个跟踪变量(largestsmallest),以及循环内的两个比较。
  • 请考虑“整齐”地格式化您的代码示例。尤其是当它们涉及多层嵌套时,如果没有缩进就很难阅读它们。
  • 查看 Math.minMath.max 以帮助比较值并允许自动分配

标签: java max minimum


【解决方案1】:

最简单的解决方案是使用 Math.minMath.max 之类的东西

double largest = a.nextDouble();
double smallest = largest;
while (a.hasNextDouble()) {
    double input = a.nextDouble();
    largest = Math.max(largest, input);
    smallest = Math.min(smallest, input);
}

【讨论】:

    【解决方案2】:
    double largest = a.nextDouble();
    double smallest = largest;
    while (a.hasNextDouble()) {
        double input = a.nextDouble();
        if (input > largest) {
            largest = input;
        }
        if (input < smallest) {
            smallest = input;
        }
    }
    

    【讨论】:

      【解决方案3】:

      以同样的方式跟踪最小值。

      public static void main(String args[])
      {
          Scanner a = new Scanner (System.in);
          System.out.println("Enter inputs (This program calculates the largest and smallest input):");
      
          double firstInput = a.nextDouble();
          double largest = firstInput;
          double smallest = firstInput;
          while (a.hasNextDouble())
          { 
              double input = a.nextDouble();
              if (input > largest)
              {
                  largest = input;
              }
              if (input < smallest)
              {
                  smallest = input;
              }
          }
      
          System.out.println("Largest: " + largest);
          System.out.println("Smallest: " + smallest);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-25
        • 1970-01-01
        相关资源
        最近更新 更多