【问题标题】:I can't find smallest number by this code. How I find smallest number by modifying this code?我无法通过此代码找到最小的数字。如何通过修改此代码找到最小的数字?
【发布时间】:2021-03-09 06:24:19
【问题描述】:

没有其他错误。我就是无法打印最小的输入。

public static void main(String args[]){
    Scanner input=new Scanner(System.in);
    System.out.print("Marks of a student(-1 to terminate the inputting marks): ");
    int x=input.nextInt();
    int total=0,large=0,y=0,small=0,z;
    z=x;
    while(x!=-1){
        System.out.print("Marks of a student(-1 to terminate the inputting marks): ");
        x=input.nextInt();
        total+=x;
        y++;
        if(x>=large){
            large=x;
        }
        if(x<small){
            small=x;
        }
    }
    int sum=total+z+1;
    double avg=(double)total/y;
    System.out.println("No of students: "+y);
    System.out.println("Total marks   : "+sum);
    System.out.println("Maximum       : "+large);
    System.out.println("Minimum       : "+small);
    System.out.println("Average       : "+avg);
}

【问题讨论】:

  • small初始化为较大的值(如Integer.MAX_VALUE)

标签: java for-loop while-loop min


【解决方案1】:

small 初始化为0,因此任何大于该值的输入都将被忽略。

一种方法是使用Integer.MAX_VALUE 对其进行初始化,因此任何输入的数字都将小于或等于它。同样,large 可以用Integer.MIN_VALUE 初始化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2015-07-16
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 2020-12-15
    相关资源
    最近更新 更多