平均值/最大值来自ArrayList

huangapple go评论72阅读模式
英文:

Avg/Max from ArrayList

问题


public class LabProgram {
    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        int count = 0, max = 0, total = 0;

        int num = scnr.nextInt();

        if (num >= 0) {
            count++;
            total += num;
            max = Math.max(max, num);
            num = scnr.nextInt();
        }

        int avg = count == 0 ? 0 : total / count;
        System.out.println(avg + " " + max);
    }
}
英文:

I've had a ton of issues with this program, added a while hasNextInt, multiple other things and i've finally got the code working, but my output is just the first input, instead of max/avg of the inputs. Could somebody let me know where i'm messing up?


public class LabProgram {
   public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        int count = 0, max = 0, total = 0;

        int num = scnr.nextInt();
        
            if (num >= 0) {
               count++;
               total += num;
               max = Math.max(max, num);
               num = scnr.nextInt();
         }

        int avg = count == 0 ? 0 : total/count;
        System.out.println(avg + " " + max);
    }
}

</details>


# 答案1
**得分**: 1

你没有使用循环从控制台获取数字。此外,计算平均值的逻辑可能会得出错误的答案。请查看下面的解决方案。

```java
Scanner scnr = new Scanner(System.in);
int count = 0, max = 0, total = 0;

System.out.println("输入任何非数字字符以终止输入:");

while(scnr.hasNextInt()) {
   int num = scnr.nextInt();
   if (num >= 0) {
       count++;
       total += num;
       max = Math.max(max, num);
   }
}
double avg = count == 0 ? 0 : (double)total/(double)count; // 为了正确输出平均值
System.out.println(avg + " " + max);

示例输出:

输入任何非数字字符以终止输入:
3
3
34
a
13.333333333333334 34
英文:

you are not using a loop to get numbers from the console. Also, logic for avg may result in the wrong answer. find below solution.

 Scanner scnr = new Scanner(System.in);
 int count = 0, max = 0, total = 0;

 System.out.println(&quot;Enter any other characters expect numbers to terminate:&quot;);

while(scnr.hasNextInt()) {
   int num = scnr.nextInt();
   if (num &gt;= 0) {
       count++;
       total += num;
       max = Math.max(max, num);
   }
   }
  double avg = count == 0 ? 0 : (double)total/(double)count; // to print correct  avg
  System.out.println(avg + &quot; &quot; + max);

sample Output:

Enter any other characters expect numbers to terminate:
3
3
34
a
13.333333333333334 34

huangapple
  • 本文由 发表于 2020年10月8日 09:10:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/64254413.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定