我目前正在制作一个程序,用 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 循环相比更强大。为了解决这个问题,您需要初始化 i
和 j
与 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;
}
}
}
关于c++ - 用 c++ 编写一个程序,生成一个带星号的三角形,但结果总是差 2 个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32614441/