学習問題は、すでに提供されている数の桁根を見つけることです。先生は私たちに 2638 という数字を教えてくれました。数字の根を見つけるには、各数字を別々に足す必要があります 2 + 6 + 3 + 8 = 19. 次に、結果の 19 を取り、それらの 2 つの数字を足し合わせます 1 + 9 = 10 . もう一度同じことを行います 1 + 0 = 1. 桁根は 1 です.
私の最初のステップは、変数 total を使用して数値 2638 を合計し、合計 19 を見つけることでした。次に、2 番目の while ループを使用して、% を使用して 2 桁を分離しようとしました。
基本的な整数演算 (+、-、、/) を使用して問題を解決する必要があります。
1.ネストされたwhileループを使用して問題を解決する必要があるか、または可能ですか?
2.私の計算は正しいですか?
3.ここに書いたように、Eclipseでは動作しません。while ループを正しく使用していますか?
import acm.program.*;
public class Ch4Q7 extends ConsoleProgram {
public void run(){
println("This program attempts to find the digit root of your number: ");
int n = readInt("Please enter your number: ");
int total = 0;
int root = total;
while (n > 0 ){
total = total + (n %10);
n = (n / 10);
}
while ( total > 0 ){
root = total;
total = ((total % 10) + total / 10);
}
println("your root should be " + root);
}
}