简体   繁体   中英

Value of int doesn't change in for loop

I'm building a simple class in Java that is used in order to calculate the value of Pi, and print the real value of Pi at it's side. The program's input is a string of a natural number (bigger than 0) which is used to determine the precision of the calculation. This is my code:

public class Pi {

public static void main(String[] args) {
    int N = Integer.parseInt(args[0]);
    double myPi = 0;
    for (int i=0 ; i<N ; i++) {
        myPi += (Math.pow(-1,i))*(1/((i*2)+1));
    }
    myPi *= 4;
    System.out.println(myPi + " " + Math.PI);

}

(*there's missing closing brackets only here in the text for some reason)

The problem is that the variable "myPi" only changes for the first iteration of the for loop. For example, for the input 4 (N=4) the result will be 4.0 instead of 3.1....

Couldn't find a solution for this one, thanks!

(1/((i*2)+1)) 

the above expression is evaluated to 0 in every case except for i == 0 as it is an integer division and the expected value is a fraction which evaluates to 0

You need to use floating point arithmetic in order to get a float value.

(1.0/((i*2)+1)) <-- Note the 1.0 here

if you want to a double value as a result an operation, at least one operand must be double. try this

    int N = Integer.parseInt(args[0]);
    double myPi = 0;
    for (int i=0 ; i<N ; i++) {
        myPi += (Math.pow(-1,i))*(1.0/((i*2)+1));
    }
    myPi *= 4;
    System.out.println(myPi + " " + Math.PI);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM