如何在C++的帕斯卡三角形中打印曲棍球棒的元素?

How to print the elements of a hockey stick in a pascal triangle in C++?

本文关键字:曲棍球 打印 元素 三角形 C++ 帕斯卡      更新时间:2023-10-16

曲棍球棒的起始行号和长度将作为输入。我们需要打印曲棍球棒的元素,不包括总和。

以下代码打印包含 10 行(行:0 到 行:9(的帕斯卡三角形。如何添加代码以获取曲棍球棒的元素?

#include<iostream>
using namespace std;
int main()
{
int l, r, arr[10][10];
for (int i=0; i<=9; i++)
{
for(int j=0; j<=i; j++)
{
if((i==j)||(j==0))
{
arr[i][j] = 1;
cout << arr[i][j] << " ";
}
else
{
arr[i][j] = arr[i-1][j-1]+arr[i-1][j];
cout << arr[i][j] << " ";
}
}
cout << endl;
}

return 0;
}

它给出的输出如下,

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1

现在我们需要取曲棍球棒的起始排和长度, 让我们以 起始排-3 长度-4

1
1 1
1 2 1
**1** 3 3 1
1 **4** 6 4 1
1 5 **10** 10 5 1
1 6 15 **20** 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1

母猪曲棍球棒的形成会像,

1+4+10+20 = 35

我们需要打印最终输出如下,

1+4+10+20

注意:无需打印总和元素-35

======================================我添加了如下代码,

cout <<"enter starting row-n";
cin >> r;
cout << "enter length of hockey stick-n";
cin >> l;
cout << "nelements of hockey stick-n";
int j=0;
for (int i=r; i<=(r+l-1); i++)
{
int j = i-r;
cout << arr[i][j] << " ";
}
cout << endl;

输出为 -

enter starting row-
3
enter length of hockey stick
4
elements of hockey stick-
1 4 10 20

但我需要它如下所示。

1+4+10+20

圣黑猫的暗示通常是正确的...

。除了最后一个元素也会加上+后缀。

这就是为什么我建议扭转它:用+作为除第一个元素之外的每个元素的前缀。这是通过空的初始分隔符字符串实现的。它在循环结束时被覆盖:

const char *sep = "";
//int j=0; // unused
for (int i=r; i<=(r+l-1); i++)
{
int j = i-r;
cout << sep << arr[i][j];
sep = " + ";
}
cout << endl;

注意:

除了第一次迭代之外,可能需要对循环sep的分配。AFAIK,这通常比额外的if测试便宜。