只有一个内环的打印图案

Printing pattern with only one inner loop

本文关键字:打印 有一个 内环      更新时间:2023-10-16
*****
****
***
** 
*

使用多个内循环很容易打印出来。我正在尝试仅使用一个内部循环来做到这一点。

有什么建议吗?

谢谢大家。如果 n 是动态的怎么办?如果 n 是 10 或 5 或 100,你怎么做?

如果 n 为 3,

***
**
*

如果 n 为 5

*****
****
***
** 
*

条件:必填:一个内环,一个外环,仅cout语句。没有内置函数。

如果需要更多澄清,请告诉我。

法典:

#include <iostream>
using namespace std;
int main() {
int rows = 10;
for(int i = rows; i >= 1; --i) {
for(int k = 1; k <= (rows - i); k++) {
cout  << "  ";
}
for(int j = 1; j <= i; ++j)
{
cout << " " << "*";
}
cout << endl;
}
}

我如何只有一个内部循环来实现这一点?

内循环 ?你为什么需要这样的东西?您可以使用单个 for 循环std::string::string

void print_stuff(unsigned width){
for(auto i = 0u ; i < width ; i+=1){
auto starAmount = width - i;
auto spaceAmount = i;
std::cout << std::string{spaceAmount, ' '} << std::string{starAmount, '*'} << 'n';
}
}

如果你真的需要一个内部循环,那么只需用循环替换std::string的构造函数

void print_stuff(unsigned width){
for(auto i = 0u ; i < width ; i+=1){
//auto starAmount = width - i;
auto spaceAmount = i;
for(auto j = 0u ; j < width ; j+=1)
std::cout << (j < spaceAmount ? ' ' : '*');
std::cout << 'n';
}
}
相关文章: