如何在C++的帕斯卡三角形中打印曲棍球棒的元素?
How to print the elements of a hockey stick in a pascal triangle in C++?
曲棍球棒的起始行号和长度将作为输入。我们需要打印曲棍球棒的元素,不包括总和。
以下代码打印包含 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
测试便宜。
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 打印数字图案
- Log4cpp:以UTC/GMT时区打印日期
- 如何在C++的帕斯卡三角形中打印曲棍球棒的元素?