输入n, 求y1=1!+3!+…m!(m是小于等于n的最大奇数) y2=2!+4!+…p!(p是小于等于n的最大偶数)。
基础题,先递归构造阶乘函数,再根据输入定义m,p,循环求y1,y2;
但是注意阶乘和t1,t2是全局变量,不能直接在if else 里边定义。
代码:
#include<stdlib.h>
#include<stdio.h>
#include<iostream>
using namespace std;
int jiecheng(int x){
if(x==1){
return 1;
}
else if(x==2){
return 2;
}
else
{
x=x*jiecheng(x-1);
// cout<<"阶乘为"<<x<<endl;
return x;
}
}
int main(){
int n,m,p;
while(cin>>n){
if(n%2==0){
m=n-1,p=n;
}
else{
m=n,p=n-1;
}
int t1=0,t2=0;//暂存运算结果,y1和y2可算作边界条件
for(int i=1;i<=m;i=i+2){
t1=t1+jiecheng(i);
}
for(int i=2;i<=p;i=i+2){
t2=t2+jiecheng(i);
}
cout<<t1<<" "<<t2<<endl;
}
return 0;
}