2014年12月26日 星期五

java程式設計題目---數字處理【數字拆解(使用method)】

Write a method that computes the sum of the digits in an integer. Use the following method header:
public static int sumDigits(long n)
For example, sumDigits(234) returns 9 (2+3+4). Use a loop to repeatedly extract and remove the digit until all the digits are extracted. Write a test program thar prompts the user to enter an inter an integer and displays the sum of all its digits.


  1. import java.util.Scanner;
  2.  
  3. public class C1
  4. {
  5. public static void main(String[] args)
  6. {
  7. Scanner input = new Scanner(System.in);
  8. //提示使用者輸入整數
  9. System.out.println("請輸入整數:");
  10. int number = input.nextInt();
  11. //呼叫 sumDigits 並印出答案
  12. System.out.println(sumDigits(number));
  13. }
  14.  
  15. public static int sumDigits(int num )
  16. {
  17. int sum = 0;
  18. while( num > 0)
  19. {
  20. int a = num % 10; //將整數拆解成1位1位
  21. int b = num / 10; //拆掉一位後剩下的數字
  22. sum = sum + a ; // 將拆解後的數字加入總和
  23. num = b ;
  24. }
  25. return sum; //回傳結果
  26. }
  27. }

沒有留言:

張貼留言

Go(Golang)程式語言 設定GCC

下載MSYS2:  https://www.msys2.org/ 安裝 程式開始執行後輸入: pacman -Syu y y 在安裝目錄底下找到msys2.exe,雙擊執行 輸入指令: pacman -Su pacman -S --needed base-devel mingw-...