Java – Math.pow example

A simple Math.pow example, display 2 to the power of 8.

In Math

2^8 = 2x2x2x2x2x2x2x2 =256

In Java

Math.pow(2, 8)

Note
In Java, the symbol ^ is a XOR operator, DON’T use this for the power calculation.

TestPower.java

package com.mkyong.test;

import java.text.DecimalFormat;

public class TestPower {

    static DecimalFormat df = new DecimalFormat(".00");

    public static void main(String[] args) {

        //1. Math.pow returns double, need cast, display 256
        int result = (int) Math.pow(2, 8);
        System.out.println("Math.pow(2, 8) : " + result);

        //2. Wrong, ^ is a binary XOR operator, display 10
        int result2 = 2 ^ 8;
        System.out.println("2 ^ 8 : " + result2);

        //3. Test double , display 127628.16
        double result3 = Math.pow(10.5, 5);
        System.out.println("Math.pow(10.5, 5) : " + df.format(result3));

    }

}

Output

Math.pow(2, 8) : 256
2 ^ 8 : 10
Math.pow(10.5, 5) : 127628.16
“`

發佈了1 篇原創文章 · 獲贊 4 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章