yiwei
yiwei

Reputation: 4190

java double is not calculating correctly

I'm making this program for a class and I need to guess a number's cube root. Here's my code:

int N = Integer.parseInt(args[0]);

//sets the guess at 1.0
guess = 1.0;

//whether or not the guess is close to N
while (guess * guess * guess <= N ){

     double show = (guess + ((1/3) * ((N / (guess * guess)) - guess)));
     System.out.println(show);
     guess = show;
     continue;

}

However, every time I run this program, the double show is always set to the value 1. Can anyone please tell me why this is happening and how I can fix it?

Upvotes: 0

Views: 2324

Answers (3)

Borgleader
Borgleader

Reputation: 15916

1/3 = 0

because 1/3 is integer division and that is always 0. It should be

1.0/3.0

Upvotes: 3

Chris Dargis
Chris Dargis

Reputation: 6053

The problem is integer division. 1 / 3 = 0.

Change it to 1.0 / 3.0

BTW, there is no point for the continue statement...

Upvotes: 3

Greg Hewgill
Greg Hewgill

Reputation: 994629

The constant expression (1/3) is calculated using integer arithmetic, leaving 0. Try using (1.0/3.0). Or alternately,

 double show = (guess + (((N / (guess * guess)) - guess)) / 3.0);

Upvotes: 3

Related Questions