用c++编写程序,生成一个带有星星的三角形,但结果总是差两个数字

Making a program in c++ that will produce a triangle with stars, but the result is always 2 numbers off

本文关键字:结果 三角形 两个 数字 星星 一个 程序 c++      更新时间:2023-10-16

我目前正在编写一个程序,用c++输出一个由星星(或星号)组成的小三角形,我遇到了一些问题。

似乎每当我向函数中写入一些内容时,编译器都会将其解释为那个数字- 2——我觉得这很奇怪。

int makePyramid(int len=1) {
    // A pyramid (or triangle) can not consist of less than 1 length.
    if(len < 1) {
        cout << "does not make sense" << endl;
    }
    else {
        // Go through the length
        for(int i = 1; i < len; ++i) {
            // Make one star for each number in the last loop
            for(int j = 1; j < i; ++j) {
                cout << "*";
            }
            // Makes a new line after the second loop is through
            cout << endl;
        }
    }
}

这是所讨论的函数。正如您所看到的,它应该可以工作-第一个循环遍历整个数字,然后进入下一个循环,根据数字的值打印一个星号,然后它输出新的一行,以便它可以开始处理下一组星号。

请记住,我对c++很陌生,我在cmd (Windows 10)中使用minGW来编译代码。

1)循环for (int i = 1; i < len; i++)迭代len - 1次。i的取值范围为[1; len - 1]

2)循环for (int j = 1; j < i; ++j)迭代j - 1次。j的取值范围为[1; i - 1]

这就是为什么这些函数打印的星号更少。与Pascal循环相比,C风格的循环更复杂,也更强大。为了解决这个问题,您需要将ij初始化为0或将<替换为<=:

int makePyramid(int len=1) {
    // A pyramid (or triangle) can not consist of less than 1 length.
    if(len < 1) {
        cout << "does not make sense" << endl;
    }
    else {
        // Go through the length
        for(int i = 0; i < len; ++i) {
            // Make one star for each number in the last loop
            for(int j = 0; j <= i; ++j) {
                cout << "*";
            }
            // Makes a new line after the second loop is through
            cout << endl;
        }
    }
}

第一个循环应该从0开始或将条件更改为<=

for( int i = 0; i < len; ++i )

for( int i = 1; i <= len; ++i )

虽然第一个在c++中更常用,因为它通常用于迭代数组索引(从0到N-1)。对你来说,这无关紧要。

在第二个循环中,您必须将condition更改为<=,并从与i相同的数字开始,因此:

 for( int i = 0; i < len; ++i )
     for( int j = 0; j <= i; ++j )

 for( int i = 1; i <= len; ++i )
     for( int j = 1; j <= i; ++j )