Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Need help finding what's wrong with this code?
I did an exercise in my programming class about a pi calculator using the German mathematician Gottfried Leibniz's method to approximate pi: pi/4 = 1 - 1/3 + 1/5 - 1/7 + . . .
This is my code:
import java.util.Scanner;
public class Pi
{
public static void main(String[]args)
{
Scanner reader = new Scanner(System.in);
double pi = 1;
int denominator = 3;
int count = 0;
int sign = 0;
System.out.print("Enter the number of cycles: ");
int cycles = reader.nextInt();
System.out.println(cycles);
while(count <= cycles)
{
if(sign == 0)
{
pi = pi - (1 / denominator);
denominator = denominator + 2;
sign = 1;
count++;
}
else
{
pi = pi + (1 / denominator);
denominator = denominator + 2;
sign = 0;
count++;
}
}
System.out.println(pi * 4);
}
}
It looks like it should work, but no matter what the input is I always get 4. Not even my classmate who's practically a genius at programming nor the teacher know what's wrong. I'm not being graded on this but I just need to know what's wrong.
2 Answers
- 10 years agoFavorite Answer
the problem is idiotic.....u'll die laughing.
declare denominator as a double and not int.
i realised that java is truncating the denominator to an integer if it is an int.
so 1/denominator is always 0 and pi never changes. thats why u got 4 in the end
- modulo_functionLv 710 years ago
When you say
(1/denominator)
and denominator is an int, the result will be truncated. Either change denominator to double or use
1.0/denominator
+add
You didn't ask but I'll suggest an easier way to get that sign change:
int sign = -1.0;
while( count < cycles ) {
...pi = pi + sign*(1.0/denominator);
...denominaor = denominator + 2;
...sign = -1*sign;
...count++;
}