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

Application of loop in Java development

无忌哥哥
无忌哥哥Original
2018-07-23 10:42:421219browse

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

	}

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!

Statement:
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