Reputation: 33
So I've written a programme used to solve a concrete equation having been given one parameter int n. The code I have is:
static double getSolution1(int n)
{
double [] a = new double[n+1];
a[0] =-1;
for (int i = 1; i < n+1; i++)
{
a[i] = a[i-1] * ( ( 2 / ( 3 * n ) ) * Math.cos(2 * a[i-1]) );
}
return a[n];
}
As far as I can tell, the code works fine and should be filling in the various parts of the array. But that's not happening, apart from a[0] = -1 that I have told the programme, it is treating all other entries as 0 as though it has not undergone the loop. Using a debug, that's the only problem I can really find. How can I fix that?
Upvotes: 0
Views: 50
Reputation: 223
the expression ( 2 / ( 3 * n ) return an integer type. so for every number between 1 and 0, int type will be 0. what you can do is to let compiler treats 2 and 3 as float type or double type. you can use 2.0 instead of 2. or 3.0 instead of 3
Upvotes: 0
Reputation: 11006
As Pulkit said, 2/3 *n yields zero. Why?
Integer division will always round down your result to the nearest whole number. So:
2 / 3 = .666
floor(.666) = 0
To prevent this, you can add f
to the end of 2 or 3. That'll cause the operation to evaluate as a float rather than an integer, avoiding the rounding.
2f / 3f
You can also add d
to 2 or 3. That'll cause the operation to evaluate as a double rather than an integer.
2d / 3d
Upvotes: 0
Reputation: 859
The "2 / ( 3 * n )" is being evaluated as int; and it works out as 0.
To fix, change it to "2.0 / (3.0 * n)"
Upvotes: 0
Reputation: 1325
2 / 3 *n would give you zero, use all floats or doubles like 2.0f 3.0f
Upvotes: 1