第7周作業1-迴圈大戰
阿新 • • 發佈:2019-02-12
for迴圈語句:
import java.util.Scanner; public class FactorialTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.print("請輸入一個正整數:"); Scanner ScNumber=new Scanner(System.in); int num=ScNumber.nextInt(); System.out.println(); int p = num; for(int i=1;i<num;i++) { p=p*(num-i); } System.out.println(num+"!="+p); } }
執行結果:
while語句:
import java.util.Scanner; public class FactorialTest1 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.print("請輸入一個正整數:"); Scanner ScNumber=new Scanner(System.in); int num=ScNumber.nextInt(); System.out.println(); int p=num; int i=1; while(i<num) { p=p*(num-i); i++; } System.out.println(num+"!="+p); } }
執行結果:
do.......while語句:
import java.util.Scanner; public class FactorialTest2 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.print("請輸入一個正整數:"); Scanner ScNumber=new Scanner(System.in); int num=ScNumber.nextInt(); System.out.println(); int p=num; int i=1; do { p=p*(num-i); i++; }while(i<num); System.out.println(num+"!="+p); } }
執行結果: