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

标签 c++

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

似乎每当我向函数写入内容时,编译器都会将其解释为该数字减去二 - 我觉得这很奇怪。

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] 范围内.

这就是为什么这些函数打印较少星号的原因。 C 风格的循环很棘手,并且与例如 Pascal 循环相比更强大。为了解决这个问题,您需要初始化 ij0或者通过替换 <<= :

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;
        }
    }
}

关于c++ - 用 c++ 编写一个程序,生成一个带星号的三角形,但结果总是差 2 个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32614441/

相关文章:

c++ - 需要一个例子来说明默认构造函数没有被继承

c++ - 如何将 const ref 返回给结构对象,使其所有嵌套结构也都是只读的?

c++ - 如何迭代具有相同基类的元素元组

c++ - 我应该为 `size_t` 包含哪个 header ?

c++ - Qt Ui 存在但 Ui header 和源不存在

c++ - 在 C++ 中,如果按下回车键,我如何制作 cin "cancel"?

java - 在 C++ 中是否有一个具有类似功能的 TreeSet 数据结构?

c++ - OpenCV - 使用 C++ 填充对象中的空白区域

c++ - const 引用与特定示例的混淆

c++ - 如何使用 C++ 形式的 TextBox 文本?