简体   繁体   中英

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. 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 5 25 125 625 3125 15625

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

15625 15625 15625 15625 15625 15625

256 256 256 256 256 256 256 256

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? I want to use the Math.pow Method

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 :

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

And printing k again and again in loop.

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

You should be changing value of k as well. 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. The value i that changes during for each loop iteration isn't used at all.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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