繁体   English   中英

这段代码能更有效吗?

[英]Can this code be more efficient?

该程序应该这样做

N 10*N 100*N 1000*N
1 10  100    1000
2 20  200    2000
3 30  300    3000
4 40 400     4000
5 50 500    5000

所以这是我的代码:

public class ex_4_21 {

    public static void main( String Args[] ){

    int process = 1;
    int process2 = 1;
    int process22 = 1;
    int process3 = 1;
    int process33 = 2;

    System.out.println("N   10*N   100*N   1000*N");
    while(process<=5){

        while(process2<=3){
        System.out.printf("%d   ",process2);

        while(process22<=3){
            process2 = process2 * 10;
            System.out.printf("%d     ",process2);
            process22++;
        }
        process2++;
        }


        process++;
    }

    }
}   

我的代码可以更有效吗? 我目前正在学习while循环。 到目前为止,这是我得到的。 任何人都可以提高效率,或者给我一些想法,使我的代码更高效吗?

这不是家庭作业,我是在自学Java

您可以使用单个变量n来执行此操作。

 while(n is less than the maximum value that you wish n to be)
     print n and a tab
     print n * 10 and a tab
     print n * 100 and a tab
     print n * 1000 and a new line
     n++

如果10的幂是可变的,则可以尝试以下操作:

 while(n is less than the maximum value that you wish n to be)
    while(i is less than the max power of ten)
        print n * i * 10 and a tab
        i++
    print a newline
    n++

如果必须使用while循环

public class ex_4_21 {

public static void main( String Args[] ){

int process = 1;

System.out.println("N   10*N   100*N   1000*N");
while(process<=5){

    System.out.println(process + "  " + 10*process + "  " + 100*process + "  " + 1000*process + "\n");
    process++;
}

}
}

您的while循环太多(您的“ process2” while循环是不必要的)。 您似乎还存在一些与以下事实有关的错误:您在内部循环中循环的变量没有在每次迭代中都重新初始化。

我也建议不要使用while循环。 您的示例更适合for循环; 我了解您正在尝试学习循环机制,但是学习的一部分还应该在于确定何时使用哪种构造。 这实际上不是性能建议,而是方法建议。

对于您正在尝试做的事情,我没有任何进一步的性能改进建议。 您显然可以删除循环(降至单个循环,甚至不循环),但是两个循环对于您的工作有意义(允许您以最少的更改轻松地将另一行或另一列添加到输出中)。

您可以尝试循环展开,类似于@Vincent Ramdhanie的回答。

但是,对于这么小的样本,循环展开和线程处理不会显着提高性能。 与简单的while循环相比,创建和启动线程(进程)所涉及的开销要花费更多的时间。 I / O的开销比展开版本节省的时间更多。 复杂的程序比简单的程序难于调试和维护。

你想被称为microoptimization。 仅在无法满足要求或客户要求时才将优化保存在较大的程序中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM