首页 > 解决方案 > 使用 if 找出三个数中最小的数

问题描述

所以我很困惑那些 if 括号中的内容,代码工作正常但我不明白?

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);    
    int a = scanner.nextInt(); 
    int b = scanner.nextInt();
    int c = scanner.nextInt();
    if(b < a) {
      a = b; //This part is confusing to me
    }
    if(c < a) {
      c = a; 
    }    
    System.out.println("Smallest number is " + a);
}

标签: javaif-statementintjava.util.scanner

解决方案


a用于两个目的:

  1. 它正在存储第一个输入。
  2. 如果该新值较小,则将使用新值(来自其他变量,从输入中获取其值)对其进行更新。

如果我正在编写程序,我不会将这两个职责都指定给a,但这就是这里发生的事情。


推荐阅读