求和的阶乘-请求第二个代码
C++ Sum of factorial -Request 2nd code
我想分析一下我的代码算法的复杂性。因此,我必须有两个不同的程序提供相同的功能,才能让我开始。
目前是我自己的代码。
我不确定是否允许,我希望有人可以自愿提供他自己的方式代码来为我计算阶乘的总和作为第二个程序代码。
最好是嵌套循环。
#include <iostream>
using namespace std;
int main()
{
int val;
int i;
int a = 0;
int c = 1;
cout << "Please enter a number: ";
cin >> val;
cout << endl;
for (i = 1; i <= val; i++)
{
c = c * i;
a = a + c;
}
cout << "The sum of the factorials is " << a << endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int val;
cout << "Please enter a number: ";
cin >> val;
cout << endl;
static const int results[] = {
0, 1, 3, 9, 33, 153, 873, 5913, 46233, 409113,
4037913, 43954713, 522956313
};
cout << "The sum of the factorials is " << results[val < 0 ? 0 : val] << endl;
system("pause");
return 0;
}
请注意,我复制了原始程序中的缺陷,如果用户输入0
,它会导致返回不正确的值。
这个替代版本假定为32位整数,因为它利用了溢出行为。扩展到64位整数是一个练习。
我不明白你用另一种嵌套的方式做什么,但我希望这能帮助…
#include <iostream>
using namespace std;
int main()
{
int val;
int i;
int a = 0;
int c = 1;
cout << "Please enter a number: ";
cin >> val;
cout << endl;
for (i = 1; i <= val; i++){
c *= i;
a += c;
}
int c2=1;
for (i = val; i > 1; i--){
c2*=i;
c2++;
}
cout << "The sum of the factorials is " << a << endl;
cout << "The sum of the factorials is " << c2 << endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int suma = 0;
int n = 0;
cout << "Sum of factorialsn";
cout << "-------------------------------n";
cout << "Insert number of n: ";
cin >> n;
int i = 1;
while (i <= n)
{
int factorial = 1;
for(int j=1; j<=i; j++)
{
factorial = factorial * j;
}
suma += factorial;
i++;
}
cout << "Sum of factorials is: " << suma;
system("pause");
return 0;
}
相关文章:
- 我有两个类需要在同一 cpp 文件中相互引用,但第一个类无法识别第二个类类型的对象
- 等待整个 omp 块完成,然后再调用第二个函数
- 我想在C++中读取一些多个字符,但它永远不会读取第二个字符
- 为什么第二个代码给出了预期的结果,而第一个代码却没有?
- 为什么第一个代码块产生垃圾值,而第二个代码块将类成员的值相加?
- 为什么我的代码没有对数组中第二个索引上的数据进行排序?
- 为什么第二个代码有效而第一个代码无效?
- 代码未C++打印第二个字符数组
- exc_bad_access(代码= 1,地址= 0x68)在第二个读取方法中
- 如何在我的代码中修复无穷循环?我认为它跳过了第二个CIN,因此它一直在循环
- 当执行此代码中的第二个语句时,内部会发生什么
- 这段代码出了什么问题?它在第二个 cin 可以执行之前终止
- 两个GCC编译了相同的输入,生成了两个不同的代码(第二个错误)
- §7.1.6.3/1 (C++14) 不接受下面第二个代码段中的构造。这是为什么呢?
- 为什么我在第一个代码中出现分段错误,而在第二个代码中却没有
- 求和的阶乘-请求第二个代码
- 我在 c++ 代码的这一部分中找不到第二个常量实用程序,有人可以解释一下吗?
- 我不明白为什么编译代码片段的第二个版本。AFAIK 它不应该,因为 §10.3/2
- 当条件满足时,此代码不会切换到第二个while代码,如何解决此问题?
- 什么可能导致第一个代码片段的输出不同于第二个和第三个