首页 > 解决方案 > 打印空心直角三角形

问题描述

我遇到了这个 c++ 代码的问题。它应该打印一个空心的右等腰三角形,但只是一遍又一遍地打印星号,所以 for 循环似乎被卡住了。

#include "pch.h"
#include <string>
#include <iostream>

int main() {
    int row;
    std::string s = "  ";
    std::string a = " *";
    int rows = 10;

    for (int i = 0; i < rows; i++) {

        if (i = 0) {
            std::cout << a << std::endl;
        }

        while (i > 2 && i < rows) {
            std::cout << a;

            for (int pos = 0; pos < i; pos++) {
                std::cout << s;
            }

            std::cout << a << std::endl;
        }

        std::cout << a << a << a << a << a << a << a << a << a << std::endl;

    }
}

标签: c++

解决方案


您的while循环条件永远不会变为假,并且您需要==在此行中使用比较()而不是赋值:

        if (i = 0) {

推荐阅读