用一個for循環(huán)計算1+3+5+7+...+99的值,并輸出計算結(jié)果。
用一個for循環(huán)計算1!+2!+3!+...+10!的值,并輸出計算結(jié)果。
輸出1~100內(nèi)的前5個可以被3整除的數(shù)。
輸出101~200內(nèi)的質(zhì)數(shù)。
//用一個for循環(huán)計算1+3+5+7+...+99的值,并輸出計算結(jié)果。public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int add = 0; for (int i = 1; i <= 99; i += 2) { add += i; } System.out.打印的結(jié)果:
1+3+5+7+...+99 = 2500
1 //用一個for循環(huán)計算1!+2!+3!+...+10!的值,并輸出計算結(jié)果。 2 public class Test { 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 long result = 0; 9 long f=1;10 for (int i = 1; i <= 10; i++) {11 f=f*i;12 result+=f;13 14 }15 System.out.println("1!+2!+3!+...+10! = "+result);16 }17 } 打印的結(jié)果: 1!+2!+3!+...+10! = 4037913 1 //輸出1~100內(nèi)的前5個可以被3整除的數(shù)。 2 public class Test2 { 3 4 /** 5 * @param args 6 */ 7 public static void main(String[] args) { 8 // TODO Auto-generated method stub 9 int num = 0, i = 1;10 while(i <= 100){11 if(i % 3 == 0){12 System.out.println(i + " ");13 num++;14 }15 if(num == 5)16 break;17 i++; 18 }19 20 }21 22 }打印結(jié)果: 3 6 9 12 15
1 // 輸出101~200內(nèi)的質(zhì)數(shù)。 2 public class Test2 { 3 4 /** 5 * @param args 6 */ 7 public static void main(String[] args) { 8 // TODO Auto-generated method stub 9 for (int i = 101; i < 200; i += 2) {10 boolean f = true;11 for (int j = 2; j < i; j++) {12 if (i % j == 0) {13 f = false;14 break;15 }16 }17 if (!f)18 continue;19 System.out.print(" " + i);20 }21 }22 }
新聞熱點(diǎn)
疑難解答