Java Math.pow example

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

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

References

  1. Math.pow JavaDoc
  2. Wikipedia Exclusive or (XOR)

上一篇: Java Display double in 2 decimal places
下一篇: Gradle Create Java project structure automatically
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号