1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| public class JBT2404 { public static void main(String[] args) { int n = 10, m = 5; System.out.println("for循环求解下的结果是=" + sum1(n, m)); System.out.println("while循环求解下的结果是=" + sum2(n, m)); System.out.println("do while循环求解下的结果是=" + sum3(n, m)); }
public static long sum1(int n, int m) { int i = 0; long sum = 0; for (i = 1; i <= n; i++) { if (i % m == 0) { sum = sum + i; } } return sum; }
public static long sum2(int n, int m) { int i = 0; long sum = 0; while (i <= n) { if (i % m == 0) { sum = sum + i; } i = i + 1; } return sum; }
public static long sum3(int n, int m) { int i = 0; long sum = 0; do { if (i % m == 0) { sum = sum + i; } i = i + 1; } while (i <= n); return sum; } }
|