不为第一个for循环添加+计数(在嵌套for循环的情况下)

时间:2018-02-11 15:16:32

标签: java iteration

我有一个带有3个for循环的迭代函数。我使用一个数组,并希望计算迭代函数的指令数量。但是我用于数组的循环也导致计数增加1.如何删除它。这是我的代码:

package itrative.methods;

import java.util.Scanner;

public class ItrativeMethods {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i, j, k;
        int count1 = 0, count2 = 0, count3 = 0;
        int[] n = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        for (int m = 0; m < n.length; m++) {

            for (i = n[m] / 2; i <= n[m]; i++) {
                count1++;
                for (j = 1; j <= n[m] / 2; j++) {
                    count2++;
                    for (k = 1; k <= 100; k = k * 2) {
                        count3++;
                    }
                }
            }
            System.out.println(count1 + "  |  " + count2 + "  |  " + count3);
        }
    }

}

These are the results of this code (wrong)
Correct results at n=10 without using array loop

1 个答案:

答案 0 :(得分:0)

以下是在每次迭代期间如何计算值。

public class ItrativeMethods {

public static void main(String[] args) {
    int i, j, k;
    int count1 = 0, count2 = 0, count3 = 0;
    int[] n = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    for (int m = 0; m < n.length; m++) {
        count1 = 0;
        count2 = 0;
        count3 = 0;
        for (i = n[m] / 2; i <= n[m]; i++) {
            count1++;
            for (j = 1; j <= n[m] / 2; j++) {
                count2++;
                for (k = 1; k <= 100; k = k * 2) {
                    count3++;
                }
            }
        }
        System.out.println(count1 + "  |  " + count2 + "  |  " + count3);
    }
}

}

制作输出:

2  |  0  |  0
2  |  2  |  14
3  |  3  |  21
3  |  6  |  42
4  |  8  |  56
4  |  12  |  84
5  |  15  |  105
5  |  20  |  140
6  |  24  |  168
6  |  30  |  210

获得总数:

public class ItrativeMethods {

public static void main(String[] args) {
    int i, j, k;
    int count1 = 0, count2 = 0, count3 = 0;
    int count1Total = 0, count2Total = 0, count3Total = 0;
    int[] n = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    for (int m = 0; m < n.length; m++) {
        count1 = 0;
        count2 = 0;
        count3 = 0;
        for (i = n[m] / 2; i <= n[m]; i++) {
            count1++;
            count1Total++;
            for (j = 1; j <= n[m] / 2; j++) {
                count2++;
                count2Total++;
                for (k = 1; k <= 100; k = k * 2) {
                    count3++;
                    count3Total++;
                }
            }
        }
        System.out.println(count1 + "  |  " + count2 + "  |  " + count3);
    }
    System.out.println("Totals");
    System.out.println(count1Total + "  |  " + count2Total + "  |  " + count3Total);
}

}