0

Problem: Statistics are often calculated with varying amounts of input data. Write a program that takes any number of non-negative integers as input, and outputs the average and max. A negative integer ends the input and is not included in the statistics.

Ex: When the input is: 15 20 0 5 -1

the output is: 10 20

You can assume that at least one non-negative integer is input.

import java.util.Scanner; 

public class LabProgram {
   public static void main(String[] args) {

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

     do {

         total += num;
         num = scnr.nextInt();
         count = ++count;


         if (num >= max) {
            max = num;
         }

      } while (num >= 0);

     avg = total/(count-1);

      System.out.println(avg + " " + max);

   }
}

I had a lot of trouble with this problem. Is there any way I could have done this without having to do count -1 while computing the average? Also, is this this the most efficient way I could have done it?

4

3 回答 3

1
import java.util.Scanner; 

public class LabProgram {
   public static void main(String[] args) {

      Scanner scnr = new Scanner (System.in);
      int userNum;
      int maxNum = 0;
      int totalSum = 0;
      int averageNum;
      int count = 0;

      userNum = scnr.nextInt();

      while (userNum >= 0) {

         if (userNum > maxNum) {
            maxNum = userNum;
         }

         totalSum += userNum;
         ++count;

         userNum = scnr.nextInt();
      }
      averageNum = totalSum / count;

      System.out.println("" + averageNum + " " + maxNum);
   }
}

于 2020-02-07T01:12:00.600 回答
1

这个怎么样?如果您对实施有疑问,请询问。

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

        int num = scnr.nextInt();
        while (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);
    }

如果您使用 while 循环而不是 do-while 循环,则不必再计算负数输入。不,这不是最有效的方法,但这是一个好的开始!

于 2019-07-05T02:05:49.790 回答
0
      int Num;
      int max = 0;
      int total = 0;
      int average;
      int count = 0;

      Num = scnr.nextInt();

      while (Num >= 0) {

         if (Num > max) {
            max = Num;
         }

         total += Num;
         ++count;

         Num = scnr.nextInt();
      }
      average = total / count;

      System.out.println("" + average + " " + max);
   }
}
于 2020-09-30T21:51:47.773 回答