猿问

写一个函数,求一个数组a[ ]中,从第int start 到int end之间的所有元素阶乘的和?

写一个函数,求一个数组a[ ]中,从第int start 到int end之间的所有元素阶乘的和


慕尼黑8549860
浏览 968回答 3
3回答

慕斯709654

#include <stdio.h>int main(void){int start;int&nbsp;end;long sum=0;int i,j;long fac=1;printf("输入start和end的值:");scanf("%d%d",&start,&end);for(i=start ; i<=end ; i++){for(j=1;j<=i;j++)fac*=j;sum+=fac;}printf("%d!+...+%d!=%ld",start,end,sum);return 0;}程序只能实现很小范围的阶乘,因为long型的数最大只有 2147483648&nbsp;

慕码人2483693

#include <iostream>using namespace std;long factorial(int n){if(n == 1) return n;return n*factorial(n - 1);}long fun(int *a, int start, int end){long sum = 0;for(int i = start; i <= end; i++){sum += factorial(a[i - 1]);}return sum;}void main(){int a[5] = {1, 2, 3, 4, 5};cout<<fun(a, 3, 4)<<endl;}303*2*1 +4*3*2*1 = 30

烙印99

int factorial(int&nbsp;num){int i = 0;int result = 1;for(int i = 1;i <&nbsp;num+1; i++){result = i * result;}return result;}int fun(int* a, int start, int end){int result = 0;for(int i = start; i < end + 1;i++){result = result + factorial(a[i]);}return result;}
随时随地看视频慕课网APP
我要回答