我不能用这个代码找到最小的数字如何通过修改这个代码来找到最小的数字?

niwlg2el  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(390)

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

  1. public static void main(String args[]){
  2. Scanner input=new Scanner(System.in);
  3. System.out.print("Marks of a student(-1 to terminate the inputting marks): ");
  4. int x=input.nextInt();
  5. int total=0,large=0,y=0,small=0,z;
  6. z=x;
  7. while(x!=-1){
  8. System.out.print("Marks of a student(-1 to terminate the inputting marks): ");
  9. x=input.nextInt();
  10. total+=x;
  11. y++;
  12. if(x>=large){
  13. large=x;
  14. }
  15. if(x<small){
  16. small=x;
  17. }
  18. }
  19. int sum=total+z+1;
  20. double avg=(double)total/y;
  21. System.out.println("No of students: "+y);
  22. System.out.println("Total marks : "+sum);
  23. System.out.println("Maximum : "+large);
  24. System.out.println("Minimum : "+small);
  25. System.out.println("Average : "+avg);
  26. }
dgjrabp2

dgjrabp21#

small 初始化为 0 ,因此任何大于该值的输入都将被忽略。
一种方法是用 Integer.MAX_VALUE ,因此任何输入的数字都将小于或等于它。同样地, large 可以初始化为 Integer.MIN_VALUE .

相关问题