Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating nth root of a positive integer in Java

My task is to write a program which prompts the user to enter a positive double a and an integer n greater than 2, and print the value of the nth root of positive integer a to the screen with accuracy to 100 places. I've used Math.pow to be able to get the root, and I feel as though I've done everything right. The only problem is that every time I run my program, the output is 1.0, no matter what numbers I input for a and n. What is the problem with my code?

import java.util.Scanner;
import java.lang.Math;

public class Q8 {

    public static void main(String[] args) {

    System.out.println("Enter a positive number: ");
    Scanner in = new Scanner(System.in);
    double a = in.nextDouble();

    System.out.println("Enter an integer greater than 2: ");
    Scanner in2 = new Scanner(System.in);
    int n = in.nextInt();

    System.out.println(pow (a,n));
    }

private static double pow(double a, int n) {
      if (n == 0){
            return 1;
      }

      else{
         double sum = Math.pow(a,(1/n));
         return sum;
}

Why is the answer always 1.0?

like image 527
Ibrewster Avatar asked Dec 11 '22 02:12

Ibrewster


1 Answers

Replace 1/n with 1.0/n.

You're getting integer division, so no matter what n is, if it's 2 or higher, then 1/n is coming out zero. Then you're raising your number to the zeroeth power, which gives 1.

Replacing 1 with 1.0 makes the division into a floating point division - that is, the result won't be truncated to an integer. This is what you want.

like image 181
Dawood ibn Kareem Avatar answered Dec 13 '22 16:12

Dawood ibn Kareem