As shown in the figure above, the addition is implemented. It can be implemented in two ways;
One: subtract even numbers and add odd numbers.
public static void main(String[] args) { // TODO Auto-generated method stub Scanner con=new Scanner(System.in); int n=con.nextInt(); double m=0.0; for(int i=1;i<=n;i++) { if(i%2==0) {m=m-1.0/i;} else {m=m+1.0/i;} } System.out.println(m); }
Another one: set a symbol and let its symbol change with the cycle.
public static void main(String[] args) { // TODO Auto-generated method stub Scanner con=new Scanner(System.in); int n=con.nextInt(); double m=0.0; int f=1; for(int i=1;i<=n;i++) { m=m+f*1.0/i; f=-f; } System.out.println(m); }
The above is the detailed content of Application of loop in Java development. For more information, please follow other related articles on the PHP Chinese website!