简体   繁体   中英

Input numbers until 0, then calculate average

Okey, i need to make a program to calculate average. But, i need to input numbers, and when i want to stop i can input zero. Then, my program need to sum all entered numbers and calculate average of entered numbers. I made almost everyithing in my code but idk how to make a formula to calculate average, my program sum numbers and then divide by last entered number.

    Scanner input = new Scanner(System.in);
    System.out.println("Input numbers, 0 for stop!");
    int number = input.nextInt();
    int number1 = 1;
    while (number != 0) {
        number1 = (number + number1) / number; //here is my problem?
        number = input.nextInt();
    }
    System.out.println("Average is: " + number1);

Your code is written great except you calculate the average wrong,

If you want to calculate the average on the fly you will need to know how much numbers you have read so far..

eg:

Scanner input = new Scanner(System.in);
System.out.println("Input numbers, 0 for stop!");
int number = input.nextInt();
int average = number;
int counter = 1;
while (number != 0) {
    average= (average * counter + number) / (counter + 1);
    counter++;
    number = input.nextInt();
}
System.out.println("Average is: " + average);

this code will give you the average after each step.

Another (simpler solution) is:

Scanner input = new Scanner(System.in);
    System.out.println("Input numbers, 0 for stop!");
    int number = input.nextInt();
    double sum = 0;
    int counter = 0;
    while (number != 0) {
        sum += number;
        counter++;
        number = input.nextInt();
    }
    System.out.println("Average is: " + sum/counter);

Average is the sum total of the numbers divided by the number of numbers, so you need to keep a running count of how many numbers you are inputting, as well as a running sum, and at the end, you divide the sum by the count. The sum should be a double just in case you end up with a fraction

Scanner input = new Scanner(System.in);
System.out.println("Input numbers, 0 for stop!");
double sum = 0;
int count = 0;
int number = input.nextInt();
while (number != 0) {
    sum += number;
    count++;
    number = input.nextInt();
}
System.out.println("Average is: " + sum/count);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM