Home > Java > javaTutorial > Application of loop in Java development

Application of loop in Java development

无忌哥哥
Release: 2018-07-23 10:42:42
Original
1304 people have browsed it

Application of loop in Java development

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);

	}
Copy after login

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);
	}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template