使用C++打印Floyd三角形

Use C++ to Print a Floyd triangle

本文关键字:三角形 Floyd 打印 C++ 使用      更新时间:2023-10-16

我正在尝试构建一个程序,该程序将接受用户的数字并创建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的世界中(CC++JavaC#等),数组从索引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
    }
}