如何使用C++打印此图案
How to print this pattern using C++?
如何打印
*000
**00
***0
****
在这里,我们必须将行数作为用户的输入,然后打印图案。我能够打印 *,但无法打印 0 和它们一起<</p>
cout << "*000" << endl << "**00" << endl << "***0" << endl << "****" << endl;
因为啤酒很少 我会开始用同样愚蠢的答案回答愚蠢的问题。 :D祝技术面试好运。
这类问题通常旨在测试有效使用循环的技能。
使用这个:
#include<iostream>
using namespace std;
int main()
{
int length; //no of lines
cout<<"Enter the number of lines"<<endl;
cin>>length;
cout<<endl;
for( int i = 0; i < length; i++)
{
for( int j=0;j<=i;j++ )
{
cout<<"*";
}
for( int k=length-1; k>i;k-- )
{
cout<<"0";
}
cout<<endl;
}
return 0;
}
更改长度值以更改行数
我猜你正在寻找类似的东西:
int lines = 4; // lines you want to print
for (int i=1; i<=lines; i++)
{
for (int j=0; j<i; j++)
cout << "*";
for (int j=0; j<lines-i; j++)
cout << "0";
cout << endl;
}
使用
printf 比使用 cout 更容易。使用这个:
for(int i = 1; i <= 4; ++i) {
printf("%.*s%.*sn", i, "****", 4 - i, "0000");
}
printf 允许将宽度和精度字段指定为参数列表的一部分,这与 cout 不同,COUT 是内联硬编码的。有了这个提示,我将留给您弄清楚其余的。如有任何问题,请在下面发表评论。:)
坚持使用 0 索引和明确定义的不变量怎么样?
#include <iostream>
using namespace std;
int main()
{
int lines = 5;
// we have written i rows thus far
// write [i, lines) rows
for (int i = 0; i < lines; ++i)
{
// we have written j stars thus far
// write [j, i + 1) stars
for (int j = 0; j < i + 1; ++j)
{
cout << "*";
}
// we have written k zeros thus far
// write [k, lines - 1 - i) zeros
for (int k = 0; k < lines - 1 - i; ++k)
{
cout << "0";
}
cout << endl;
}
return 0;
}
相关文章:
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 如何使用gdb制作一个可以漂亮地打印每个对象的C++函数
- 我应该如何修改此代码以使用给定字符串中的字母打印菱形图案
- 使用 SFML 和 C++ 将 Pixel 打印到屏幕上
- 如何使用递归打印修改后的星号三角形图案
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何使用 std::variant 打印地图键/值?
- C ++如何使用UTF8十六进制代码打印UTF8符号?
- 访问和打印元组中的数据,并使用 C++14 使用模板函数显示数据
- C++声明双链表,使用两个 for 循环双向遍历列表并打印
- 使用递归 c++ 打印模式
- 在 c++ 中对字符串使用复制函数时打印的垃圾值
- 如何在逗号后使用 cout 打印整数值,而无需在逗号后添加额外的零C++?
- 我的C++程序如何访问计算机的日期和时间以打印和使用当前年份?
- 如何打印 ;符号使用 CMake 命令
- 打印出使用地图实现的Trie中的所有单词
- 你如何打印出使用数组删除某些字符的回文
- 将卡片的矢量传递到函数中进行打印和使用
- 打印在使用%.22f时改变的值