3 回答

TA貢獻1797條經驗 獲得超6個贊
代碼有問題是死循環 while(n>0){循環中沒有重新給n賦過值總是大于0會一直循環的。
這樣就行了
import java.util.Scanner;
public class Ex5_2 {
public static int sumDIgits(long n){
int result = 0;
while(n>0){
result = (int) (n%10 +result);
n = n/10;
}
return result;
}
public static void main(String[] args) {
System.out.println("Please Input a long number:");
Scanner sc = new Scanner(System.in);
Ex5_2 ex = new Ex5_2();
System.out.println(ex.sumDIgits(sc.nextLong()));
}
}

TA貢獻1772條經驗 獲得超8個贊
while(n>0){
tmp = m.intValue();
result = tmp%10 +result;
tmp = tmp/10;
}
你這是個死循環啊,n永遠大于0
希望可以幫助你

TA貢獻1765條經驗 獲得超5個贊
import java.util.Scanner;
public class Ex5_2 {
public int sumDIgits(long n){
int tmp;
int result = 0;
Long m = new Long(n);
tmp = m.intValue();
while(tmp>0){
result = tmp%10 +result;
tmp = tmp/10;
}
return result;
}
public static void main(String[] args) {
System.out.println("Please Input a long number:");
Scanner sc = new Scanner(System.in);
System.out.println(Ex5_2.sumDIgits(sc.nextLong()));
}
}
- 3 回答
- 1 關注
- 178 瀏覽
添加回答
舉報