Calculating powers of integers

前端 未结 16 2061
情书的邮戳
情书的邮戳 2020-12-08 06:18

Is there any other way in Java to calculate a power of an integer?

I use Math.pow(a, b) now, but it returns a double, and that is usually a

16条回答
  •  清歌不尽
    2020-12-08 06:38

    import java.util.*;
    
    public class Power {
    
        public static void main(String args[])
        {
            Scanner sc=new Scanner(System.in);
            int num = 0;
            int pow = 0;
            int power = 0;
    
            System.out.print("Enter number: ");
            num = sc.nextInt();
    
            System.out.print("Enter power: ");
            pow = sc.nextInt();
    
            System.out.print(power(num,pow));
        }
    
        public static int power(int a, int b)
        {
            int power = 1;
    
            for(int c = 0; c < b; c++)
                power *= a;
    
            return power;
        }
    
    }
    

提交回复
热议问题