gpt4 book ai didi

java - 编写一个程序来读取未指定数量的整数

转载 作者:行者123 更新时间:2023-12-01 16:59:26 28 4
gpt4 key购买 nike

“计算正数和负数并计算数字的平均值)编写一个程序,读取未指定数量的整数,确定读取了多少个正值和负值,并计算输入值的总和和平均值(不是计数零)。您的程序以输入 0 结束。将平均值显示为 float 。”

我不知道我做错了什么

import java.util.Scanner;

public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

int positive = 0, negative = 0, total = 0, count = 0;

double average;

System.out.println("Enter the number: ");
int number;

while ((number = input.nextInt()) != 0) {
total += number;
count++;
if (number > 0) {
positive++;
} else if (number < 0) {
negative++;
}
}
average = total / count;
System.out.println("The number of positives is " + positive);
System.out.println("The number of negatives is " + negative);
System.out.println("The total is " + total);
System.out.printf("The average is %d ", average);
}
}

最佳答案

第一:应该是average = (double)total / count;因为 int/int 比你得到一个整数。

第二个:System.out.println("The average is " + average);System.out.printf("The average is %f ", average);

关于java - 编写一个程序来读取未指定数量的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28840042/

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