繁体   English   中英

除以零时出现 ArithmeticException 错误。 但我不是。 为什么?

[英]I am getting an ArithmeticException Error for dividing by zero. But I am not. Why?

这是我要解决的编码问题

编写一个程序,从键盘读取两个数字 aa 和 bb,计算区间 [a; 中所有数字的算术平均值并将其输出到控制台。 b][a;b],可以被 33 整除。

样本输入 1:
-5
12

样品 Output 1:
4.5

这是我的代码:

import java.util.Scanner;

class Main {

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

        double average = 0;
        int a = scanner.nextInt();
        int b = scanner.nextInt();

在此处输入图像描述

问题:引发算术异常

问题是什么?

您的变量 i 从 -5 循环到 12。然后,您将 (a + b) / i 相除(第 14 行)。

0 介于 -5 和 12 之间。因此,您最终将除以零。

(我假设第 13 行应该防止这种情况发生,但是按照您编写它的方式,它不会。事实上,0 是 i 的极少数值之一,实际上将执行第 14 行。)

根据您的示例输入和示例 output,您需要将范围内可被 3 整除的所有数字相加,然后将该总数除以该范围内有多少个不同的数字。

在 -5 和 12 之间,能被 3 整除的数是:

-3、0、3、6、9、12

当你把它们加在一起时,你得到 27。
总共有6个不同的数字。
所以平均值是 27 除以 6 得到 4.5

现在是代码。

import java.util.Scanner;

public class RangeAvg {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter lower bound: ");
        int a = scanner.nextInt();
        scanner.nextLine();
        System.out.print("Enter upper bound: ");
        int b = scanner.nextInt();
        int lower = Math.min(a, b);
        int upper = Math.max(a, b);
        int total = 0;
        int count = 0;
        for (int i = lower; i <= upper; i++) {
            if (i % 3 == 0) {
                System.out.println(i);
                total += i;
                count++;
            }
        }
        System.out.println("total = " + total);
        System.out.println("count = " + count);
        if (count > 0) {
            double average = (double) total / count;
            System.out.println("average = " + average);
        }
        else {
            System.out.printf("No numbers divisible by 3 between %d and %d%n", lower, upper);
        }
    }
}

下面是一个示例运行:

Enter lower bound: -5
Enter upper bound: 12
-3
0
3
6
9
12
total = 27
count = 6
average = 4.5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM