如何显示用户插入的指数函数的展开形式?

我正在使用 for 循环来计算整数的幂。用户可以输入:

  • int a,它是整数本身

  • int b,它是整数的幂

最后,我应该以扩展形式显示结果。我被困在这一步了。有人可以帮忙吗?

我尝试在 for 循环内嵌套 while 循环,但这似乎不起作用。

//power of an integer


//interacting with user

import java.util.Scanner;


public class Exercise2{

    public static void main (String[] args){


        //ready to accept input

        Scanner input = new Scanner (System.in);

        System.out.println("Enter an integer: ");

            int a = input.nextInt();

            System.out.println("What power do you want " + 

                        a + "to be raised to? ");

            int b = input.nextInt();


            int count=2;


        //for loop

        for (int i =1 ; i<=1; i++){


            //output data

            System.out.println((int)Math.pow(a,b));


            }

        }


    }

}

结果是 Math.pow() 产生的双精度值;仍然没有扩展的形式。e.g.: 4^3 display: 4 x 4 x 4。


翻过高山走不出你
浏览 90回答 2
2回答

尚方宝剑之说

您的for循环构建不正确。for (int i = 1 ; i <= 1; i++)只会执行循环体一次。这是一个根据需要打印第一个变量a,b次数的解决方案。该程序还进行任意检查b > 0以确保结果可以以扩展形式表示。public static void main(String[] args) {&nbsp; &nbsp; Scanner input = new Scanner(System.in);&nbsp; &nbsp; System.out.println("Enter an integer: ");&nbsp; &nbsp; int a = input.nextInt();&nbsp; &nbsp; System.out.println("What power do you want " + a + " to be raised to? ");&nbsp; &nbsp; int b = input.nextInt();&nbsp; &nbsp; if (b > 0) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(a);&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 1; i < b; i++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(" x " + a);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(a + "^" + b + " cannot be expanded!");&nbsp; &nbsp; }}

青春有我

你可以这样做StringJoiner j = new StringJoiner ("×","","");for(int i=0; i<b;i++){&nbsp;j.add(a+""); }System.out.print(j.toString());这段代码只是以这种形式打印,假设 a=3 b=4,所以输出是 3×3×3×3,这样你就可以用 Math.pow 方法来计算输入的结果
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java