簡體   English   中英

線程“ main”中的異常java.lang.ArithmeticException:/減零-查找因素

[英]Exception in thread “main” java.lang.ArithmeticException: / by zero - finding factors

此方法采用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);
        }
    }
}

問題在於,當i為0時,t%i是不確定的,因為您無法除以零,也無法找到余數。

您應該從1開始,而不是從0開始循環。

更改

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

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

(您也可以考慮從2開始測試,因為1是所有整數的因數)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM