簡體   English   中英

Java 有指數運算符嗎?

[英]Does Java have an exponential operator?

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

沒有運算符,但有一種方法。

Math.pow(2, 3) // 8.0

Math.pow(3, 2) // 9.0

僅供參考,一個常見的錯誤是假設2 ^ 3是 2 的 3 次方。 它不是。 插入符號是 Java(和類似語言)中的有效運算符,但它是二進制異或。

要使用用戶輸入執行此操作:

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)Math.pow(double a, double b)這樣的(int)Math.pow(double a, double b)

最簡單的方法是使用 Math 庫。

使用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);

您可以使用 Math 類中的 pow 方法。 以下代碼將輸出 2 升至 3 (8)

System.out.println(Math.pow(2, 3));

如果有人想使用遞歸創建自己的指數函數,以下供您參考。

public static double power(double value, double p) {
        if (p <= 0)
            return 1;

        return value * power(value, p - 1);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM