用c++编写程序,生成一个带有星星的三角形,但结果总是差两个数字
Making a program in c++ that will produce a triangle with stars, but the result is always 2 numbers off
我目前正在编写一个程序,用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风格的循环更复杂,也更强大。为了解决这个问题,您需要将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;
}
}
}
第一个循环应该从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 )
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- valgrind-hellgrind与泄漏检查的结果不同
- 用C++20 fmt限制结果的总大小
- 如何返回一个类的两个对象相加的结果
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 绘制旋转的三角形
- 序列化,没有库的整数,得到奇怪的结果
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 在更改for循环的第三部分后,未使用for循环结果
- 使用++运算符会导致意外的结果
- 如何用for循环在c++中生成单词三角形
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- C++Brute Force攻击函数不会返回结果
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 在CGAL中查找两个二维三角形的相交/差的三角化结果
- 用c++编写程序,生成一个带有星星的三角形,但结果总是差两个数字
- C++:查找直角三角形算法没有得到预期的结果
- C++:帕斯卡三角形 - 奇怪的结果