书中的示例要求用户输入任何正数。然后程序将分别添加各个数字并打印总数。例如,如果用户输入数字 7512,则程序设计为将 7 + 5 + 1 + 2 相加,然后打印总数。
我已经写出了我理解代码如何工作的方式。它是否正确?我对这个循环的理解是否正确,或者我错过了任何计算?当 7 % 10 中没有余数时,在第 4 次循环中会发生什么?
1st run of loop ... sum = sum + 7512 % 10 which is equal to 2
n = 7512 / 10 which which equals to 751
2nd run of loop ... sum = 2 + 751 % 10 which is equal to 1
n = 751 / 10 which is equal to 75
3rd run of loop ... sum = 3 + 75 % 10 which is equal to 5
n = 75 / 10 which is equal to 7
4th run of loop ... sum = 8 + 7 % 10 <------?
import acm.program.*;
public class DigitSum extends ConsoleProgram{
public void run() {
println("This program will add the integers in the number you enter.");
int n = readInt("Enter a positive integer: ");
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
println("The sum of the digits is" + sum + ".");
}
}