有人可以用 Java 向我解释一下代码吗? % 和/= 如何得到输入的所有总和?我对代码的逻辑感到困惑。谢谢。
(对整数中的数字求和)编写一个程序,读取 0 到 0 之间的整数 1000 并将整数中的所有数字相加。例如,如果整数是 932,则 其所有数字之和为 14。 提示:使用 % 运算符提取数字,使用/运算符删除 提取的数字。例如,932 % 10 = 2 和 932/10 = 93。
import java.util.Scanner;
public class Exercise_02_06 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Create new Scanner object
// Prompt the user to enter a number between 0 and 1000.
System.out.print("Enter a number between 0 and 1000: ");
int number = input.nextInt();
// Compute the sum of the digits in the integer.
int lessThan10 = number % 10;
number /= 10;
int tens = number % 10;
number /= 10;
int hundreds = number % 10;
number /= 10;
int sum = hundreds + tens + lessThan10;
// Display results
System.out.println("The sum of the digits is " + sum);
}
}
最佳答案
% 是余数运算符。所以 14 % 10 是 4。对于整数算术,除以后的分数会被丢弃。所以 14/10 是 1。
So follow this.
total = 0
numb = 932
int n = numb % 10 = 932 % 10 = 2
total = total + n = 2
numb = numb /10 = 93
n = numb % 10 = 93 % 10 = 3
total = total + n = 2 + 3 = 5
numb = numb / 10 = 9
n = numb % 10 = 9 % 10 = 9
total = total + 9 = 5 + 9 = 14
9 + 3 + 2 = 14
关于java - 有人可以用 Java 向我解释一下代码吗? % 和/= 如何得到输入的所有总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60179143/