C++求1!到n!的和

题目内容:求1!+2!+3!+4!+……+n!的结果。

输入描述:输入不多于50个正整数的数据n(1<=n<=12)

输出描述:对于每个n,输出计算结果。每个计算结果应单独占一行。

参考代码:

#include "stdafx.h"
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;

int main(int argc,char * argv[])
{
	vector<int> n(50);
	int sum, p, m;
	int num = 0;
	while (num <= 49)
	{
		cin >>m;
		if (m>= 1 && m<= 12)
		{
			n[num] = m;
			num++;
		}		
		else if (m<1 || m>12)
		{
			cout << "The input should be more than 1 and less than 12";
		}
		if (cin.get()=='\n')
		{
			break;
		}
	}		
	for (int j = 0; j < num; j++)
	{
		sum = 0;
		p = 1;
		for (int i = 1; i <= n[j]; i++)
		{
			p = p*i;
			sum = sum + p;			
		}
		cout << sum << endl;
	}	
	return 0;
}

结果如图:

posted @ 2013-10-20 23:18  源子陌  Views(2504)  Comments(0Edit  收藏  举报