为什么我的“While Loop"没有打印找到平均“分数"的计算? [英] Why doesn't my "While Loop" print the computation of finding the average "score"?

查看:15
本文介绍了为什么我的“While Loop"没有打印找到平均“分数"的计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序来读取用户输入的一系列正整数.用户一次只能输入一个整数.然后它会计算这些整数的平均值.当用户输入 0 时程序将结束.(0 不计入平均值).程序将在程序结束后打印出平均值.

I am writing a program that reads a sequence of positive integers input by the user. User will only enter one integer at a time.Then it will compute the average of those integers. The program will end when user enters 0. (0 is not counted in the average).The program will print out the average once the program ends.

问题:当我进入 while 循环时,我的代码停止工作,因此它不计算用户的输入,因此不打印任何内容.为什么我的 while 循环不计算用户输入的平均值?感谢您的指导:)

Question: My code stops working when I gets to the while loop hence it doesn't compute the input by user, hence prints out nothing. Why doesn't my while loop compute the average from the user's inputs? Appreciate your guidance :)

import java.util.Scanner;

public class AverageOfIntegers {

    public static void main(String[] args) {

        int integer;
        double sum;
        sum = 0;
        double average;
        Scanner input = new Scanner(System.in);
        int count; count = 0; 
        average = 0;


        System.out.println("Please enter an integer: ");

        integer = input.nextInt();


        while (integer != 0) {
        count = count + 1;  

            sum = sum + integer; 

            average = sum / count;

        }

        System.out.println("Average = " + average);

    }

}

推荐答案

这是因为您实际上从未对多个整数求和.用户只输入一个数字.因此,您的循环基本上只作用于一个数字.您需要将输入放入 while 循环中并保存运行总和并在那里计数.更像这样的

This is because you are never actually summing over more than one integer. The user only ever enters one number. As a result your loop is essentially acting on just the one number. You need to put the input inside the while loop and save a running sum and count there. Something more like this

while (integer != 0) {
    count += 1;  

        sum += integer; 

        average = sum / count;
        integer = input.nextInt();
    }

这篇关于为什么我的“While Loop"没有打印找到平均“分数"的计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆