使用C++打印Floyd三角形
Use C++ to Print a Floyd triangle
我正在尝试构建一个程序,该程序将接受用户的数字并创建Floyd三角形。
我试着使用弗洛伊德三角形的逻辑,但它被打印成了一条线。
示例:
Enter total numbers: 5
Enter the numbers: 3,8,2,4,9
O/p:
3
82
249
这是我的代码:
#include <iostream>
using namespace std;
int main()
{
int totalnos, j, i;
cout << "Enter total numbers: ";
cin >> totalnos;
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 1; i <= totalnos; i++)
{
cin >> numbers[i];
}
for (i = 1; i <= totalnos; i++)
{
for (j = 1; j <= 1; j++)
{
cout << numbers[i];
}
}
}
下面显示的循环类型有问题。我不知道这种解决方案是因为你来自Pascal世界,还是因为你在其他地方见过。无论如何,您不应该让循环从1开始到i,或者至少,您应该考虑到在类似C的世界中(C、C++,Java和C#等),数组从索引0开始,到索引n - 1
结束,n
是数组的大小。
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 1; i <= totalnos; i++)
{
cin >> numbers[i];
}
问题实际上不在于循环使用什么索引,而在于访问数组时必须始终使用0..n-1
。因此,您可以更改循环以正确访问阵列:
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 1; i <= totalnos; i++)
{
cin >> numbers[ i - 1 ];
}
或者,您可以像C类世界中的所有程序员一样,直接从0:开始索引
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 0; i < totalnos; i++)
{
cin >> numbers[i];
}
不是从1到totalnos
,而是从0到totalnos - 1
(注意i < totalnos
而不是i <= totalnos
,这是缝合线的变化)。
您访问的内存超过了数组的限制,这意味着您的程序将显示未定义的行为(这意味着它可能会崩溃,尽管在某些情况下,似乎什么都不会发生,这更危险)。
现在是算法本身。我没有听说过Floyd三角关系。它似乎是用从1开始的自然数构建的。但是,您要求的是totalnos
号码。要构建一个包含totalnos
行的Floyd三角形,需要多于totalnos
的数字。这就是为什么需要调整显示的数字的位置,同时考虑每行的列数(numPos
以0开头)。
cout << endl;
for (i = 0; i < totalnos; i++)
{
if ( ( totalnos - i ) < numPos ) {
numPos = totalnos - i;
}
for (j = 0; j < i; j++)
{
cout << numbers[numPos] << ' ';
++numPos;
}
cout << endl;
}
您可以在此处找到完整的代码:http://ideone.com/HhjFpz
希望这能有所帮助。
内部循环可以修改如下:
for (i=0; i < 3; i++)
{
for (j=0; j<=i; j++)
{
cout << numbers[i+j];
}
cout<<" ";
}
硬编码值"3"可以替换为"Floyd三角形的行数"。我想这会奏效的。
在内部循环中,您使用j<=1.应该是j<=i;并且您错过了换行符的'\n'字符
这里是修复:
#include <iostream>
using namespace std;
int main()
{
int totalnos, j, i, k = 0;
cout << "Enter total numbers: ";
cin >> totalnos;
//int numbers[totalnos];
//cout << "Enter the numbers: ";
// for (i = 1; i <= totalnos; i++)
// {
// cin >> numbers[i];
// }
for (i = 1; i <= totalnos; i++)
{
// your code for (j = 1; j <= 1; j++)
for(j=1; j<=i; ++j) // fixed
cout << k+j << ' ';
++k;
cout << endl; // fix
}
}
- 绘制旋转的三角形
- 如何用for循环在c++中生成单词三角形
- 如何使用递归打印修改后的星号三角形图案
- C++ 创建带有 for 循环的三角形
- 绘制顺时针三角形,重新排序点
- 在顶点着色器中使用 OpenGl 的未声明标识符,我在顶点着色器中绘制三角形时遇到问题
- Eigen c++ 三角形来自
- 为我的 c++ 类介绍制作一个三角形分类器.我有几个问题
- 使用对象文件读取三角形数据网格
- 从捕获的帧中裁剪三角形 - OpenCV 和 C++
- 如何从 3D 曲面网格中删除自相交三角形?
- 以C++输出一个数字三角形
- 打印对立三角形在C++中起作用
- 确定C++中的等腰直角三角形
- 是否可以使用 DirectX 3D 11 绘制由三角形组成的圆?
- 形成一个斐波那契三角形,使得每个数字是上面左对角线或右对角线上两个数字的总和
- OpenGL绘制三角形而不是正方形
- 将数字表示为两个三角形数字的总和
- OpenGL程序不显示三角形
- 使用C++打印Floyd三角形