use*_*992 51 java exponent pow
Java中是否有指数运算符?
例如,如果用户被提示输入两个数字,他们进入3和2,正确的答案应该是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);
    }
}
Pau*_*per 87
没有运营商,但有一种方法.
Math.pow(2, 3) // 8.0
Math.pow(3, 2) // 9.0
仅供参考,一个常见的错误是假设2 ^ 3是2到3的力量.它不是.插入符号是Java(和类似语言)中的有效运算符,但它是二进制xor.
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
有Math.pow(double a, double b)方法。请注意,它返回一个双精度值,您必须将其转换为 int 类型,例如(int)Math.pow(double a, double b).
最简单的方法是使用数学库.
使用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;
}
使用:
double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);
| 归档时间: | 
 | 
| 查看次数: | 286401 次 | 
| 最近记录: |