Java: The program code m (i) = 4 (1-1 / 3 + 1 / 5-1 / 7 + 1 / 9-1 / 11 .... + ((-1) ^ i + 1) / (2 * i-1))


public class Test1 {
int i=901;
double m=0;
double flag=1.0;
double b=0.0;
public void result(){
System.out.println("i “+“m(i)”);
System.out.println(“1 “+“4.0000”);
for(int a=101;a<=i;a=a+100){
b=0;
flag=1;
for(double j=1.0;j<=a;j=j+1){
b=flag/(2j-1)+b;
flag=-flag;
}
m=4
b;
String s=String.format(”%.4f”,m);
System.out.println(a+” "+s);
}
}
}
public class Test1Demo {
public static void main(String[] args){
Test1 t1=new Test1();
t1.result();
}
}

This question uses the IDEA2018 version.
In this question, I chose the double nested loop. The outer for loop is to maintain the increase of 1 101 201 301 ..., and the inner for loop is for calculation.
This question needs to be noted that after the first 101 loop ends, the values ​​of b and flag need to be re-initialized outside the second layer loop , otherwise an error will occur, and the result of 201 calculation will be wrong.
Indicates that positive and negative conversion can use flag to change the sign in the loop with flag = -flag .

When the answer is not correct, you can check the code again. If you ca n’t check it out, you can use the DEBUG function of IDEA. You can find out the problem by changing the value step by step. I have a deep experience here!
If you have questions or find errors in this article, please let me know in the comments, thanks.
This article is original, if you want to reprint, please indicate the source.
Finally, if this article is helpful to you, please give me a thumbs up!

Published 9 original articles · won 9 · visited 2167

Guess you like

Origin blog.csdn.net/grandniu/article/details/104988055
5-1
5-1