我正在尝试用c ++创建一个程序,它接受用户输入并显示Pascal三角形的特定行。 即输入3应该导致1 3 3 1。 但是当我在程序中输入3时,显示“1 1 1 1”。我认为我相当接近,但我无法弄清楚出了什么问题。
#include <iostream>
using namespace std;
int n, k, fact1, fact2, fact3, number1, number2, number3, nTakeAwayK, nChooseK;
void CalculateNChooseK();
int main()
{
cout << "Enter a row number for Pascal's Triangle: ";
cin >> n;
int x = 1;
for (int k = 0; k <= n; k++)
{
cout << x << '\t';
CalculateNChooseK();
x = nChooseK;
}
cout << endl;
system("PAUSE");
return 0;
}
void CalculateNChooseK()
{
fact1 = 1;
for (number1 = 1; number1 <= n; number1++)
{
fact1 = (fact1 * number1);
}
fact2 = 1;
for (number2 = 1; number2 <= k; number2++)
{
fact2 = (fact2 * number2);
}
nTakeAwayK = (n - k);
fact3 = 1;
for (number3 = 1; number3 <= nTakeAwayK; number3++)
{
fact3 = (fact3 * number3);
}
nChooseK = fact1 / (fact2*fact3);
}
答案 0 :(得分:1)
将您的代码修改为此..希望这会有所帮助
for (k = 1; k <= n+1; k++)
{
cout << x << '\t';
CalculateNChooseK();
x = nChooseK;
}
当您在for循环中声明k时,此值不是全局的。
for (int k = 0; k <= n; k++) // don't declare k here.. and also loop from 1 to n+1 inclusive