gpt4 book ai didi

c++ - 牛顿二项式系数C++算法

转载 作者:行者123 更新时间:2023-11-28 06:18:53 25 4
gpt4 key购买 nike

所以我们必须使用函数来计算二项式系数。为此,我创建了一个用于阶乘微积分的函数和另一个使用后者计算可能组合数量的函数。它们都运行良好(在之前的练习中已经完成)但是由于某种原因,当我现在运行我的代码时,eclipse 停止工作。它应该采用用户输入的数字(在我的代码中为 j)并与 i(从 0 开始)进行组合,直到 i等于 j。有人有想法吗?

谢谢。

#include <iostream>
using namespace std;

//factorial function
int fact(int a) {
int resultat = 1;
while (a > 0) {
resultat = resultat * a;
a = a - 1;
}
return resultat;
}

//combinations function
int combinaisons(int z, int y) {
int c;
c = ((fact(y)) / ((fact(z)) * (fact(y - z))));
return c;
}

int main() {
int i, j;
cout << "Entrez le degree" << endl;
cin >> j;
while (j < 0) {
cout << "Un nombre naturel svp!" << endl;
cin >> j;
i = 0;
}
//calculation of the binomial coefficient
while (i != j) {
cout << combinaisons(i, j) << endl;
i = i + 1;
}
return 0;
}

最佳答案

当用户第一次输入正确的值时,您未能初始化 i

使用声明初始化 i 就足够了。

此外,您还没有处理 i == j 的情况,毕竟 binom(j,j) = binom(j,0)

//change the condition
while (i <= j) {
cout << combinaisons(i, j) << endl;
i = i + 1;
}

关于c++ - 牛顿二项式系数C++算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29670425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com