310. 迴圈正偶數相加

題目:
• 設計說明:  
(1) 程式執行時,畫面顯示【請輸入 n 的值( n > 0,且為偶數):】,請使用者輸入一個正偶數。  
(2) 試利用 do-while,計算 2 +4+6+…+n的總和,其中 n 為一由鍵盤輸入的正偶數,若輸入的不是正偶數,則程式會要求使用者再次輸入,值到輸入的數是正偶數為止。  
(3) 計算 2+4+6+…+n 的總和,顯示如執行結果參考畫面(2)。
程式碼:

import java.util.Scanner;
public class JPD03_310 {

 public static void main(String[] args){
  // TODO Auto-generated method stub
  Scanner sc =  new Scanner(System.in);
   int total=0;
   int n;
   do{
    System.out.print("請輸入 n 的值( n > 0,且為偶數):");
    n = sc.nextInt();
     if(n%2==0 && n>0){
      break;
     } 
   }while(true);
   for(int i=2;i<=n;i+=2){
    total += i;
   }
   System.out.print("2+4+...+"+n+"="+total);
 }

}

留言

熱門文章