此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;
}
}
答案 0 :(得分:2)
您的while
循环条件将永远不会为假,并且您需要使用比较(==
)而不是此行中的赋值:
if (i = 0) {
答案 1 :(得分:0)
假设您要打印的内容具有以下形式: 例如。对于行= 5
*
**
* *
* *
*****
您的代码应具有以下结构:
for (int i = 1; i <= rows; ++i)
{
//special case for the first line
if (i == 1)
std::cout << asterisk << std::endl;
//for each of the other lines print 2 asterisks and the rest spaces
if (i > 1 && i <= rows - 1)
{
//one at the start of the line
std::cout << asterisk;
//print line - 2 spaces
for (int j = 0; j < i - 2; ++j)
std::cout << space;
//one at the end of the line
std::cout << asterisk << std::endl;
}
//special case for the last line
if (i == rows)
{
for (int j = 1; j <= i; ++j )
std::cout << asterisk;
std::cout << endl;
}
}
答案 2 :(得分:0)
您的while循环条件是这里的问题,如果条件,您也应该在内部使用==而不是=。无论如何,这是您解决方案中的一个小问题。
void printTriangle() {
int row;
std::string s = " ";
std::string a = " *";
int rows = 10;
for (int i = 1; i < rows-1; i++) {
for (int j = 1; j <= i; ++j)
{
if (j == 1 || j == i)
std::cout << a;
else
std::cout << s;
}
std::cout << std::endl;
}
for (int i = 1; i < rows; ++i)
std::cout << a;
}