java上机作业--等差数列

1.

package test;/*
@author wb    
@great forever
i think,therefor i am
*/

class calculate
{
    private int t,s;
    public void calculate()
    {
        s=0;
    }
    /*
    参数:数列开始,最后一位,增量
    返回:int
    */
    public int total(int first,int last,int increment)//increment为数列增量
    {
        if( ((last - first) / increment) % 1 ==0 ) //数列为等差时
        {
            for(int j=0;j<(last - first) / increment + 1;j++)
            {
                t = j*increment + first;
                s = s + t;
            }
        }
        return s;
    }
}
//测试
class test
{
    public static void main(String args[])
    {
        calculate c = new calculate();//这里创建一个对象
        System.out.println(c.total(1,9,4)); //这里调用C对象的total方法
    }
}

猜你喜欢

转载自blog.csdn.net/CSDNwbdream/article/details/83654722