在仅提示输入一个数字的情况下,我该怎么做?不是5个输入 分开的数字?我无法循环播放(我们仅在学校的第二章中),即使我知道使用它更合乎逻辑:
分配只使用%或/来查找5位整数的和
/* while( Number > 0) {
Remainder = Number % 10;
Sum = Sum + Remainder;
Number = Number / 10;
System.out.format("sum: "+ Sum);
*/
也可以有人用外行的术语解释模数和/和。谢谢!
//Scanner is in the java.util package
import java.util.Scanner; //import class
public class SumOf5Digits {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
System.out.print("Enter a 5-digit positive integer: ");
int Number1, Remainder1;
int Number2, Remainder2;
int Number3, Remainder3;
int Number4, Remainder4;
int Number5, Remainder5;
int Sum = 0;
Number1 = input.nextInt();
Number2 = input.nextInt();
Number3 = input.nextInt();
Number4 = input.nextInt();
Number5 = input.nextInt();
Remainder1 = Number1 % 10;
Number1 = Number1 /10;
Remainder2 = Number2 % 10;
Number2 = Number2 /10;
Remainder3 = Number3 % 10;
Number3 = Number3 /10;
Remainder4 = Number4 % 10;
Number4 = Number4 /10;
Remainder5 = Number5 % 10;
Number5 = Number5 /10;
Sum = Sum + (Remainder1 + Remainder2 + Remainder3 + Remainder4 +
Remainder5);
System.out.format ("sum:" + Sum);
}
答案 0 :(得分:1)
这里是一个例子:
import java.util.Scanner; //import class
public class SumOf5Digits {
public static void main(String[] args) {
// Read integer
Scanner input = new Scanner(System.in);
System.out.print("Enter a 5-digit positive integer: ");
int number = input.nextInt();
// Compute sum of up to five base-10 digits in the number
int sum = 0;
if (number > 99999) {
System.out.println("WARNING: " + number + " has more than five base-10 digits");
} else {
int digit = number % 10; System.out.println("digit[0]=" + digit);
sum += digit;
digit = (number/10) % 10; System.out.println("digit[1]=" + digit);
sum += digit;
digit = (number/100) % 10; System.out.println("digit[2]=" + digit);
sum += digit;
digit = (number/1000) % 10; System.out.println("digit[3]=" + digit);
sum += digit;
digit = (number/10000) % 10; System.out.println("digit[4]=" + digit);
sum += digit;
}
// Print sum
System.out.println("Sum=" + sum);
}
}
示例输出:
Enter a 5-digit positive integer: 22222
digit[0]=2
digit[1]=2
digit[2]=2
digit[3]=2
digit[4]=2
Sum=10