gpt4 book ai didi

java - 平均用户在 Java 中输入的数字

转载 作者:行者123 更新时间:2023-11-30 08:19:01 25 4
gpt4 key购买 nike

我正在尝试获取用户输入数字的平均值。每次我输入数字时,输出总是-

总和为6号码数量:4平均:2.0

需要一个 while 循环,不幸的是 for 循环是不允许的。我是 Java 的新手,所以我的格式很草率。我的代码中哪里有问题?

import java.util.Scanner;

public class LoopsEndingRemembering {

public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts

Scanner reader = new Scanner(System.in);
int count = 0;
int sum = 0;
int endingVariable = -1;
int input = 0;
double average;

while (input >= endingVariable) {
System.out.println("Type numbers: ");
input = Integer.parseInt(reader.nextLine());
sum += count;
average = (double)sum / count;
count++;

if (input == endingVariable) {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + count);
System.out.println("Average: " + average);
break;
}
}
}
}

最佳答案

这里有几个错误。

导致错误的主要原因是sum += count。您不是添加用户输入的内容,而是添加显示有多少个数字的数字。所以它总是会加上 0+1+2+3 等等。

另一个问题是,一旦你改变了上面的内容,你必须检查 input == endingVariable before 你将输入添加到总和。所以你必须先写if,然后计算里面的平均值。否则它会将您的 -1 视为要计算的数字序列的一部分。

如果发现输入与endingVariable不相同,只需将输入添加到总和并递增计数即可。

所以:

  • 将输入而不是计数添加到总和。
  • 仅当您到达最后一项时才计算平均值。
  • 仅当您的输入不是endingVariable 时,才将输入添加到总和并递增计数器。

关于java - 平均用户在 Java 中输入的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27045370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com