简体   繁体   English

为什么我的for循环反复打印相同的数字?

[英]why is my for loop printing the same number over and over?

Write a method called printPowersOfN that accepts a base and an exponent as arguments and prints each power of the base from base0 (1) up to that maximum power, inclusive. 编写一个称为printPowersOfN的方法,该方法接受一个底数和一个指数作为参数,并打印从base0(1)到最大底数(包括该底数)的每个底数幂。 For example, consider the following calls: 例如,考虑以下调用:

printPowersOfN(4, 3);

printPowersOfN(5, 6);

printPowersOfN(-2, 8);

These calls should produce the following output: 这些调用将产生以下输出:

1 4 16 64 1 4 16 64

1 5 25 125 625 3125 15625 1 5 25 125 625 3125 15625

1 -2 4 -8 16 -32 64 -128 256 1 -2 4 -8 16 -32 64 -128 256

public class prac {

    public static void main(String[]args) {
        printPowersOfN(4,3);
        printPowersOfN(5,6);
        printPowersOfN(-2,8);
    }

    public static void printPowersOfN(int num1, int num2) {
        int k =(int) Math.pow(num1, num2);
        for (int i=1; i<=num2;i++) {            
            System.out.print( k + " ");
        }
        System.out.println();
    }
}

My output is: 64 64 64 我的输出是:64 64 64

15625 15625 15625 15625 15625 15625 15625 15625 15625 15625 15625 15625

256 256 256 256 256 256 256 256 256256256256256256256256256256

Why is this only printing the max power over and over instead of the of all the powers leading up to the exponent?(idk if i worded that properly) What am I doing wrong? 为什么这只是一遍又一遍地打印最大功率,而不是导致指数的所有幂?(如果我说的正确的话,idk)我在做什么错? I want to use the Math.pow Method 我想使用Math.pow方法

Why is this only printing the max power over and over instead of the of all the powers leading up to the exponent? 为什么这只是一遍又一遍地打印最大功率,而不是导致指数的所有幂?

Because you are storing max power in k : 因为您将最大功率存储在k

 int k =(int) Math.pow(num1, num2);

And printing k again and again in loop. 并一次又一次地循环打印k。

System.out.print( k + " ");

You should be changing value of k as well. 您还应该更改k的值。 For example the following should work for you: 例如,以下应该适合您:

int k;
for (int i=0; i<=num2;i++) {
    k =(int) Math.pow(num1, i);
    System.out.print( k + " ");
}

You may need to make slight changes based on your requirement but this gives you a fair idea of what is going wrong. 您可能需要根据自己的要求进行一些细微的更改,但这可以使您对发生的问题有一个清晰的了解。

In you calculate the power k outside the loop and just print it over and over again. 在计算循环外的功率k ,只需一遍又一遍地打印出来。 The value i that changes during for each loop iteration isn't used at all. 每次循环迭代期间更改的值i都不会使用。

This will work Try it now 这将起作用立即尝试

public static void main(String[]args) {
    printPowersOfN(4,3);
    printPowersOfN(5,6);
    printPowersOfN(-2,8);
}

public static void printPowersOfN(int num1, int num2) {
    int k = 0;
    for (int i=0; i<=num2;i++) {            
        k =(int) Math.pow(num1, i);
           System.out.print( k + " ");
    }
    System.out.println();
}

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

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