1. ホーム
  2. java

[解決済み] Javaには指数演算子がありますか?

2022-03-04 02:25:48

質問

Javaに指数演算子はありますか?

例えば、ユーザーが2つの数字を入力するように促され、次のように入力したとします。 32 であれば、正解は 9 .

import java.util.Scanner;
public class Exponentiation {

    public static double powerOf (double p) {
        double pCubed;

        pCubed = p*p;
        return (pCubed);
    }

    public static void main (String [] args) {
        Scanner in = new Scanner (System.in);

        double num = 2.0;
        double cube;    

        System.out.print ("Please put two numbers: ");
        num = in.nextInt();

        cube = powerOf(num);

        System.out.println (cube);
    }
}

解決方法は?

ユーザーの入力で行うこと。

public static void getPow(){
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter first integer: ");    // 3
    int first = sc.nextInt();
    System.out.println("Enter second integer: ");    // 2
    int second = sc.nextInt();
    System.out.println(first + " to the power of " + second + " is " + 
        (int) Math.pow(first, second));    // outputs 9