Java 有指数运算符吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22084373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does Java have an exponential operator?
提问by user3362992
Is there an exponential operator in Java?
Java中有指数运算符吗?
For example, if a user is prompted to enter two numbers and they enter 3
and 2
, the correct answer would be 9
.
例如,如果提示用户输入两个数字并且他们输入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);
}
}
采纳答案by Jason Pather
To do this with user input:
要使用用户输入执行此操作:
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
回答by Paul Draper
There is no operator, but there is a method.
没有运算符,但有一种方法。
Math.pow(2, 3) // 8.0
Math.pow(3, 2) // 9.0
FYI, a common mistake is to assume 2 ^ 3
is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.
仅供参考,一个常见的错误是假设2 ^ 3
是 2 的 3 次方。它不是。插入符号是 Java(和类似语言)中的有效运算符,但它是二进制异或。
回答by PlasmaPower
There is the Math.pow(double a, double b)
method. Note that it returns a double, you will have to cast it to an int like (int)Math.pow(double a, double b)
.
有Math.pow(double a, double b)
方法。请注意,它返回一个双精度值,您必须将其转换为 int 类型,例如(int)Math.pow(double a, double b)
.
回答by Kedarnath Calangutkar
you can use the pow method from the Math class. The following code will output 2 raised to 3 (8)
您可以使用 Math 类中的 pow 方法。以下代码将输出 2 升至 3 (8)
System.out.println(Math.pow(2, 3));
回答by libik
The easiest way is to use Math library.
最简单的方法是使用 Math 库。
Use Math.pow(a, b)
and the result will be a^b
使用Math.pow(a, b)
,结果将是a^b
If you want to do it yourself, you have to use for-loop
如果你想自己做,你必须使用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;
}
Using:
使用:
double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);
回答by Rajesh D
In case if anyone wants to create there own exponential function using recursion, below is for your reference.
如果有人想使用递归创建自己的指数函数,以下供您参考。
public static double power(double value, double p) {
if (p <= 0)
return 1;
return value * power(value, p - 1);
}