只有一个内环的打印图案
Printing pattern with only one inner loop
*****
****
***
**
*
使用多个内循环很容易打印出来。我正在尝试仅使用一个内部循环来做到这一点。
有什么建议吗?
谢谢大家。如果 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';
}
}
相关文章:
- 有一个打印语句的函数是一种糟糕的编程实践吗
- VSCode-有一个红色下划线,但程序构建和运行正确,并且出现配音错误
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 有没有可能有一个只有ADL才能找到的非好友功能
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 我的程序有一个保存配置文件的GUI,如何双击此配置文件以直接加载带有配置数据的GUI?
- 在学习数据结构之前对STL有一个了解是好的吗?
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 我的输出中有一个额外的 0,为什么会这样
- 节点是否为空,即使它有一个值?
- 将数组信息存储到 c++ 向量中有一个"Access violation reading location"
- 在 Stream C++ 文本之前有一个额外的换行符
- 我可以有一个 ELI5 作为参考和指针以及何时使用它们吗?
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 是否有一个标准函数可以打印/监视stdin文件的内容,同时将数据留在stdin中
- 打印一个带有静态 int 的函数,有一个 std::cout 和多个 std::cout 有什么区别?
- 是否有一个很好的方法可以在C 11中打印出像JSON一样的Trie结构(仅迭代解决方案)的扁平命名空间
- 为什么我打印单链表时会有一个假节点