内存:128 时间:1
题目描述
定义一个递归函数sum,函数声明如下:
int sum(int n); //函数声明,返回12+22+32+……+n2的和
在下面代码的基础上完成,提交时只提交sum的函数定义。
#include <iostream>
#include <cmath>
using namespace std;
int sum(int n); //函数声明,求12+22+32+……+n2的和
int main()
{
int n,s;
cin>>n;
s= sum(n) ; //函数调用
cout<<s<<endl;
return 0;
}
注意:sum为递归函数
输入
正整数n的值
输出
12+22+32+……+n2的和
样例输入
5
样例输出
55
提示
注意:sum为递归函数
提交时只提交sum的函数定义。
代码如下
#include <iostream>
#include <cmath>
using namespace std;
int sum(int n); //函数声明,求12+22+32+……+n2的和
int main()
{
int n,s;
cin>>n;
s=sum(n); //函数调用
cout<<s<<endl;
return 0;
}
int sum(int n)
{
if(n==0||n==1)
return 1;
else
return sum(n-1)+n*n;
}
代码来源于互联网,仅供参考!
评论
评论功能已经关闭!