Java - exemple Math.pow
Un exemple simple deMath.pow
, affiche 2 à la puissance 8.
In Math 2^8 = 2x2x2x2x2x2x2x2 =256 In Java Math.pow(2, 8)
Note
En Java, le symbole^
est unXOR operator, NE l'utilisez PAS pour le calcul de la puissance.
TestPower.java
package com.example.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)); } }
Sortie
Math.pow(2, 8) : 256 2 ^ 8 : 10 Math.pow(10.5, 5) : 127628.16