Help with rounding slash program

 DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

# Thread: Help with rounding slash program

1. Registered User
Join Date
Nov 2005
Posts
16

## Help with rounding slash program

I made a program that calculates pie(i think it works) but the answer is always rounded i get like 4.0.
I also noticed that if i System.out.println(3/4) it doesnt output a decimal number.
Can anyone help me?
Thanks.

Edit: Btw the program should output around 3.1 something when you enter 10 as number of iterations. (around pie)

Code:
```import java.util.Scanner;
public class pie {
// pi * 4 = 1 - (1/3)+(1/5)-(1/7)+...
public static void main(String[] args) {

Scanner input = new Scanner(System.in);
int iter;
double pie;
boolean minus = true;
System.out.println("<<<< Pie Calculator >>>>");
System.out.print("\nEnter The Number of iterations to use to approximate pie: ");
iter = input.nextInt();

pie = 1.00001;

for (int i=3 ; i < iter ; i+= 2)  {

if (minus= true)		{
pie -=  1/i ;
minus = false;
}
else 			   {
pie +=  1/i;
minus = true; 	}

}

pie *= 4;

System.out.println("\nAmount of pie = " + pie +(3/4));

}
}```
Last edited by Darrel104; 10-04-2006 at 06:16 PM.

2. Registered User
Join Date
Oct 2006
Posts
1
Here is the solution you are looking for, using your code.

Code:
```import java.util.Scanner;
public class pie {
// pi * 4 = 1 - (1/3)+(1/5)-(1/7)+...
public static void main(String[] args) {

Scanner input = new Scanner(System.in);
int iter;
double pie;
boolean minus = true;
System.out.println("<<<< Pie Calculator >>>>");
System.out.print("\nEnter The Number of iterations to use to approximate pie: ");
iter = input.nextInt();

pie = 1.00001d;

for (int i=3 ; i < iter ; i+= 2)  {

if (minus)		{
pie -=  1d/(double)i ;
minus = false;
}
else 			   {
pie +=  1d/(double)i;
minus = true; 	}

}

pie *= 4d;

System.out.println("\nAmount of pie = " + pie +(3d/4d));

}
}```
Two issues here. The else would never execute because you were always assigning the value of true to minus. The comparison operator is == and you had =. Simply using minus or !minus would be sufficient.

The second issue is with your primitive data types. When performing arithmetic operations on two integer data types the result will be an integer. therefore 1/3 will always be 0 when the decimal is truncated. you must specify that the 1 and the 3 are doubles or floats by placing the d or f, respectively, behind them.
Last edited by Justin Zellers; 10-04-2006 at 09:53 PM.

3. Registered User
Join Date
Nov 2005
Posts
16
Thanks a whole lot i wouldnt of never found that out without you, never herd of that syntax rule.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 FAQ Latest Articles Java .NET XML Database Enterprise