gpt4 book ai didi

java - 一系列数字的算术平均值

转载 作者:行者123 更新时间:2023-12-01 12:23:53 25 4
gpt4 key购买 nike

声明称:

Successive integers read from the keyboard. When you read a -1, the program must indicate how many numbers between 1 and 100 we read and what is their arithmetic mean (MediaNum.java).

我推送此代码:

import java.util.*;


public class MediaNum {

public static void main(String[] args) {

Scanner entrada = new Scanner(System.in);
double number, sum=0, medium;
int counter=0;
System.out.println("When you want to finish enter '-1'.");
System.out.println("Enter the numbers:");
number = entrada.nextDouble();
while (number != -1){
sum = sum + number;
counter++;
number = entrada.nextDouble();
}
if (number == -1){
counter++;
System.out.println("counter");
}
if (number == -1 && number < 101){
medium = sum/counter;
System.out.println("The medium of the numbers entered is: "+medium);
}
}
}

介质的部分和当我输入 -1 时计数器完成的部分是正确的,但错误是当我输入超过 100 的数字时,计数器会计算该数字,并且介质将不正确。

最佳答案

只要数出符合条件的数字即可:

while (number != -1){
if(number >= 1 && number <= 100) {
sum += number;
counter++;
}
number = entrada.nextDouble();
}

关于java - 一系列数字的算术平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26491038/

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