Java是否有指数运算符?

use*_*992 51 java exponent pow

Java中是否有指数运算符?

例如,如果用户被提示输入两个数字,他们进入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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*per 87

没有运营商,但有一种方法.

Math.pow(2, 3) // 8.0

Math.pow(3, 2) // 9.0
Run Code Online (Sandbox Code Playgroud)

仅供参考,一个常见的错误是假设2 ^ 3是2到3的力量.它不是.插入符号是Java(和类似语言)中的有效运算符,但它是二进制xor.

  • 我想知道为什么`^` 是按位异或运算符(例如 Java 和 Python)的 de factor 标准 - 一定让许多初学者或 MATLAB 用户感到困惑...... (4认同)
  • 为什么单独提出java和python呢?“^”作为通用过程编程语言中的按位异或是由 C 引入的,几乎所有基于 C 的语言(或从 C 或 C++ 获得灵感)都遵循该约定。事实上,它在专用数学编程语言中意味着其他东西,这一事实不应该让任何人感到困惑吗? (2认同)

Jas*_*her 33

要使用用户输入执行此操作:

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
Run Code Online (Sandbox Code Playgroud)

  • `(double)`是完全没必要的,它输出`9.0`,而不是`9`. (6认同)

Pla*_*wer 5

Math.pow(double a, double b)方法。请注意,它返回一个双精度值,您必须将其转换为 int 类型,例如(int)Math.pow(double a, double b).


lib*_*bik 5

最简单的方法是使用数学库.

使用Math.pow(a, b)和结果将是a^b

如果你想自己做,你必须使用for循环

// Works only for b >= 1
public static double myPow(double a, int b){
    double res =1;
    for (int i = 0; i < b; i++) {
        res *= a;
    }
    return res;
}
Run Code Online (Sandbox Code Playgroud)

使用:

double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);
Run Code Online (Sandbox Code Playgroud)