我确实尝试了对我的代码进行许多修改,但我没有得到我想要的:
例如,如果我在变量 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;
}