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

标签 java

“计算正数和负数并计算数字的平均值)编写一个程序,读取未指定数量的整数,确定读取了多少个正值和负值,并计算输入值的总和和平均值(不是计数零)。您的程序以输入 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/

相关文章:

java - JSON对齐其循环相同的项目

java - Cassandra 中的特殊字符搜索

java - 计算字符串中小写字母的数量并以直方图的形式打印出它们的出现次数?

java - 安卓开发: Read outlook emails in own app activity

java - 代码抛出 SEVERE : No value specified for parameter 1 excetion

java - Java ZoneId 无法识别美国的哪些短时区 ID?

java - 在 JVM 5 或更低版本上运行 JVM 6 编译的代码

java - 为什么在 Android 9.0 中 webview 中的进度条显示有延迟?

java - 从pyspark手动调用spark的垃圾回收

java - 如何使用 LocalDateTime 解析/格式化日期? (Java 8)