如何使用 c++ 制作内部空白的三角角
How to make tri angle with blank inside using c++?
我确实尝试了对我的代码进行许多修改,但我没有得到我想要的:
例如,如果我在变量 N 中输入 7,结果将显示
*
**
* *
* *
* *
* *
*******
这是我的代码
#include <iostream>
using namespace std;
int main() {
for (int x=1; x<=N; x++){
cout<<"*";
for (int y=1; y<x; y++){
cout<<"*";
}
cout<<"n";
}
return 0;
}
我必须添加到我的代码中的内容与上述结果有关?
由于其他人建议这可能是家庭作业,这里有一些提示:
- 始终确保您有一个有效的主签名。
int main()
就足够了,没有返回类型的main()
无效。 - 启用警告。 在大多数情况下,
-Wall -pedantic
应该足够了(即,它捕获了上述错误(,但-Wextra
也可能有用。 - 使用命名空间 std; 被认为是不好的做法,因为您可能会定义与导入的名称冲突的函数或变量名称。养成打字的习惯
std::
.(例如,分配可能要求您具有distance
函数,这可能与std::distance
冲突。 - 使用描述性变量名称。对于一个微不足道的程序,
x
、y
和N
都很好,但会降低可读性。它还可以帮助您可视化您尝试解决的问题。
我们知道y
最多总是x
,因为每行的字符数应该等于当前行。例如,第 7 行应包含 7 个星号。我们只在y
不等于零或x - 1
时打印一个空格,因为这应该是我们的"边界"。最后,最后一行应包含所有星号。
// The amount of asterisks per line is [1, N]
for (int x = 1; x <= N; x++)
{
// x is the amount of characters we want to print per line
for (int y = 0; y < x; y++)
{
// If we at the beginning or end of a line, this is our "border".
// Print an asterisk.
if (y == 0 || (y + 1 == x))
std::cout << "*";
else
{
// Otherwise we are "inside" the triangle.
// If this is the last line, print all asterisks
if (x == N)
std::cout << "*";
else
std::cout << " ";
}
}
std::cout << "n";
}
此外,正如另一个答案所建议的那样,您可以通过将条件放入单个变量中来消除混淆if
结构的需要。
bool space_or_asterisk = (y == 0 || (y + 1 == x) || x == N);
std::cout << (space_or_asterisk ? '*' : ' ');
虽然你得到了几个有效的答案,但如果你消除令人困惑的if
/then
/else
语句,逻辑可能会简单得多:
#include <iostream>
int main() {
static const char chars[] = "* ";
static const int size = 7;
for (int i=0; i<size; i++) {
for (int j=0; j<size; j++)
std::cout << chars[j!=0 && i!=j && bool(i+1-size)];
std::cout << "n";
}
}
尽管逻辑显然更简单,但如果您将其作为家庭作业提交,您仍然希望确保对其进行足够的研究以回答有关它的任何问题。
main() {
for (int x=1; x<=N; x++){
for (int y=1; y<=x; y++){
if(y==1||y==x||x==N){
cout<<"*";
}else{
cout<<"*";
}
}
cout<<"n";
}
return 0;
}
相关文章:
- 无法通过空白将文本文件行分隔为矢量
- 由cin中的字符串中未捕获空白引起的分割错误
- 尝试从 XamlApplication 编译 C++/WinRT 空白应用程序时,我收到未解析的外部符号 winrt_make_*
- 代码精简版页面变为空白
- 在OpenCV C++中创建空白图像
- Gtkmm 窗口为空白,不显示任何小部件或标题
- 我如何使它,无论用户用空白字符串按 Enter 多少次,它总是打印"开始"字符串?
- OpenGL - 添加第二个着色器属性会导致空白屏幕
- 对象数组打印空白字符串
- 三角化元组
- 为什么这个Pascal三角实现给了我尾随的零
- CGAL-三角网格,返回面对面映射
- 如何在c++中读取do-while循环中的空白
- C++缓冲区是如何工作的(关于空白)
- 如何访问CGAL三维三角测量中的面
- Shell_NotifyIcon在系统托盘中创建空白、无响应的图标
- 我需要帮助修复C++空白检测器
- 接受 istream 的空白值
- CGAL 3D 周期性德劳内三角测量与信息的问题
- Fixed_alpha_shape_3() 会破坏或修改原始三角测量吗?