Java有指数运算符吗?

2022-08-31 13:07:27

Java中是否有指数运算符?

例如,如果系统提示用户输入两个数字,并且他们输入 和 ,则正确答案为 。329

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

答案 1

没有运算符,但有一种方法。

Math.pow(2, 3) // 8.0

Math.pow(3, 2) // 9.0

仅供参考,一个常见的错误是假设是2到3的幂。事实并非如此。脱字符号是Java(和类似语言)中的有效运算符,但它是二进制异或。2 ^ 3


答案 2

要使用用户输入执行此操作,请执行以下操作:

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

推荐