第二章第六题(求一个整数各位数的和)(add the digits in an integer)

    科技2022-07-10  174

    第二章第六题(求一个整数各位数的和)(add the digits in an integer)

    **2.6(求一个整数各位数的和)编写程序,读取一个0和1000之间的整数,并将该整数的各位数字相加。例如:整数是932,各位数字之和为14。 提示:利用操作符%提取数字,然后使用操作符 / 移除提取出来的数字。例如:932=2,932/10=93。 下面是一个运行示例: Enter a number between 0 and 1000:999 The sum of the digits is 27

    **2.6(add the digits in an integer) Write a program that reads an integer between 0 and 1000 and adds all the digits in the integer.for example :the integer is 932,the Summation of all its digits is 14. Hint: Use the % operator to extract digits, and use the / operator to remove the extracted digit.For instance,932 % 10 = 2 and 932 / 10 = 93. Here is a simple run: Enter a number between 0 and 1000:999 The sum of the digits is 27

    参考代码:

    package chapter02; import java.util.Scanner; public class Code_06 { public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.print("Enter a number between 0 and 1000: "); int number = input.nextInt(); int ge = number % 10; int more1 = number / 10; int shi = more1 % 10; int more2 = more1 / 10; int sum = more2 + ge + shi; System.out.format("The sum of digits is %d",sum); } } 结果显示: Enter a number between 0 and 1000: 999 The sum of digits is 27 Process finished with exit code 0
    Processed: 0.059, SQL: 8