c语言编程 输入整数n,求1+2+3+……+n和n!
#include<stdio.h>
#include<math.h>
int JieCheng(int n);
int QiuHe(int n);
int main()
{
printf("阶乘:%d\n",JieCheng(10));
printf("求和:%d\n",QiuHe(10));
}
//计算n!
int JieCheng(int n)
{
if(n==1)
{
return 1;
}
else
{
return n*JieCheng(n-1);
}
}
//求和,1+2+3+……+n
int QiuHe(int n)
{
int i;
int s=0;
for(i=1;i<=n;i++)
{
s+=i;
}
return s;
}
这样行么。
1. 使用c语言编程输入整数n,求1+2+3+……+n和n!
#include<stdio.h>
#include<math.h>
int main()
{
int i;
int nNumber;
int nSum = 0;
printf("Input Data:'N'");
scanf("%d", &nNumber);
for ( i = 1; i <= nNumber; i++)
{
nSum = nSum + i;
}
printf("%d\r\n", nSum);
return 0;
}
2. 使用c语言编程输入整数n,求1+2+3+……+n和n!
#include<stdio.h>
#include<math.h>
int Factorial(int n);
int Add(int n);
int main()
{
printf("阶乘:%d\n",Factorial(10));
printf("求和:%d\n",Add(10));
}
int Factorial(int n)
{
if(n==1)
{
return 1;
}
else
{
return n*JieCheng(n-1);
}
}
int Add(int n){
int i;
int s=0;
for(i=1;i<=n;i++)
{
s+=i;
}
return s;
}
#include "stdafx.h"
#include <stdio.h>
int main()
{
int i;
int nNumber;
int nSum = 0;
printf("Input Data:'N'");
scanf("%d", &nNumber);
for ( i = 1; i <= nNumber; i++)
{
nSum = nSum + i;
}
printf("%d\r\n", nSum);
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////
C++版本:
#include <iostream.h>
int main()
{
int nNumber;
int nSum = 0;
cout << "Input Data:'N'" << endl;
cin >> nNumber;
for ( int i = 1; i <= nNumber; i++)
{
nSum = nSum + i;
}
cout << nSum << endl;
return 0;
}