Ibrewster
Ibrewster

Reputation: 187

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?

Upvotes: 4

Views: 3088

Answers (2)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79838

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.

Upvotes: 8

Eran
Eran

Reputation: 393821

First of all, I'm assuming that

double sum = Math.pow(a,(1/root));

should be

double sum = Math.pow(a,(1/n));

since there is no root variable in your code.

Second of all, 1/n would give you 0 for every integer n > 1. Therefore sum would be 1.0. You should replace it with :

double sum = Math.pow(a,(1.0/n));

or

double sum = Math.pow(a,(1/(double)n));

In order to get a division of double variables.

Upvotes: 5

Related Questions