0
点赞
收藏
分享

微信扫一扫

day6--使用for循环完成不同步长的累加

彭维盛 2022-04-08 阅读 38
java

使用for循环完成不同步长的累加

package com.one;

public class ForStatement {

	public static void main(String[] args) {
		forStatementTest();

	}// of main
	public static void forStatementTest(){
		int tempN = 10;
		System.out.println("1 add to " + tempN + " is: " + addToN(tempN));
		
		tempN = 0;
		System.out.println("1 add to " + tempN + " is: " + addToN(tempN));
		
		int tempStepLength = 1;
		tempN = 10;
		System.out.println("1 add to " + tempN +" with step length " +tempStepLength + " is: " + addToNWithStepLength(tempN,tempStepLength));
	
		tempStepLength = 2;
		tempN = 10;
		System.out.println("1 add to " + tempN +" with step length " +tempStepLength + " is: " + addToNWithStepLength(tempN,tempStepLength));
	}// of forStatementTest
	
	public static int addToN(int paraN){
		int resultSum = 0;
		for(int i = 1 ; i<= paraN ; i++){
			resultSum += i;
		}// of for
		
		return resultSum;
	}// of addToN
	
	public static int  addToNWithStepLength(int paraN,int paraStepLength) {
		int resultSum = 0;
		for(int i = 1 ; i <= paraN ; i += paraStepLength)
		{
			resultSum += i;
		}// of for
		return resultSum;
	}// of addToNWithStepLength

}// of class

运行结果

在这里插入图片描述

举报

相关推荐

0 条评论