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

查看:56
本文介绍了为什么我的"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天全站免登陆