【问题标题】:Exception in thread "main" java.lang.ArithmeticException: / by zero - finding factors线程“主”java.lang.ArithmeticException 中的异常:/ 零 - 查找因素
【发布时间】:2013-03-19 12:58:08
【问题描述】:

此方法接受一个 int - 但是我不断收到错误消息,有人知道为什么吗?

 //finds the factors of a number that was entered
public void findFactors(int t)
{
    System.out.println("factors of " +t+ " are:");

    for(int i =0; i<t+1; i++)
    {
        if(t%i == 0)
        {
            System.out.println(i);
        }
    }
}

【问题讨论】:

    标签: java factorization


    【解决方案1】:

    问题是当 i 为 0 时 t%i 是未定义的,因为你不能除以零也不能找到余数。

    您应该从 1 开始,而不是从 0 开始循环。

    改变

    for(int i =0; i<t+1; i++)
    

    for(int i =1; i<t+1; i++)
    

    (您也可以考虑从 2 开始测试,因为 1 将是所有整数的一个因素)

    【讨论】:

      猜你喜欢
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      相关资源
      最近更新 更多