我应该编写一个程序,提示使用多行,然后在" V"中输出ASCII艺术。形状。 对于输入4,输出为(" - "表示空格):
*-----* -*---* --*-* ---*
我的代码是:
// prompt for number of stars
int stars;
std::cin >> stars;
// indent
int indent = 0;
int space = 1;
// find space
if (stars = 1)
{
space = 0;
}
else if (stars == 2)
{
space = 1;
}
else if (stars >= 3)
{
int addspace = stars - 2;
space = space + (2 * addspace);
}
// print spaces to double check calculation
std::cout << "space: " << space << '\n';
// print first star
if (stars == 1)
{
std::cout << "*";
}
// print lines
for (int lines = 1; lines == stars; ++lines)
{
// print indent
std::cout << "indent: " << indent << '\n'
<< "spaces: " << space << '\n';
if (lines > 1)
{
for (int ind_loop = 1; ind_loop < indent; ++ind_loop)
{
std::cout << " ";
}
}
std::cout << "*";
indent += 1;
// print spaces
std::cout << "spaces: " << space << '\n';
for (int sp_loop = 0; sp_loop < space; ++sp_loop)
{
std::cout << " ";
}
space -= 2;
std::cout << "*";
// next line
std::cout << '\n';
}
std::cout << '\n';
每次它只给我:
*
和int空格总是等于0。
有谁知道为什么会这样,以及我需要做些什么来纠正它?
答案 0 :(得分:3)
您的代码存在一些问题:
if (stars = 1)
始终为true,并将stars
的值更改为1.您需要将其更改为if (stars == 1)
。
for(int lines = 1; lines == stars; ++lines)
错误,因为除非stars
正好为1,否则不会执行。您需要将其更改为for(int lines = 1; lines <= stars; ++lines)
。
for(int ind_loop = 1; ind_loop < indent; ++ind_loop)
需要更改为for(int ind_loop = 0; ind_loop < indent; ++ind_loop)
,才能在第二行正确操作。
从cout
循环中移除*
以外的所有for
和空格,它们将会破坏您的V
表单。
对于循环中的最后一个std::cout << "*";
,您需要添加一个条件来检查它是否是最后一行(最后一行应该打印*
一次)
所以,最终的代码是这样的:
int main()
{
int stars;
std::cin >> stars;
// indent
int indent = 0;
int space = 1;
// find space
if(stars == 1)
{
space = 0;
}
else if(stars == 2)
{
space = 1;
}
else if(stars >= 3)
{
int addspace = stars - 2;
space = space + (2 * addspace);
}
// print spaces to double check calculation
std::cout << "space: " << space << '\n';
// print first star
if(stars == 1)
{
std::cout << "*";
}
// print lines
for(int lines = 1; lines <= stars; ++lines)
{
// print indent
//std::cout << "indent: " << indent << '\n'
// << "spaces: " << space << '\n';
if(lines > 1)
{
for(int ind_loop = 0; ind_loop < indent; ++ind_loop)
{
std::cout << " ";
}
}
std::cout << "*";
indent += 1;
// print spaces
//std::cout << "spaces: " << space << '\n';
for(int sp_loop = 0; sp_loop < space; ++sp_loop)
{
std::cout << " ";
}
space -= 2;
if(lines != stars)
std::cout << "*";
// next line
std::cout << '\n';
}
system("pause");
return 0;
}
答案 1 :(得分:-1)
你可以以一种非常紧凑的方式做同样的事情,尝试理解下面的代码与你做同样的事情,而不需要if,希望它可以帮助你编程的第一步
#include <iostream>
using namespace std;
int main ()
{
int lines,pad,cnt,i,j;
while(true)
{
cin >> lines;
for(i=lines,pad=0,cnt=(lines-2)*2+1;i>1;i--,pad++,cnt-=2)
{
for(j=0;j<pad;j++)cout<<" ";
cout<<"*";
for(j=0;j<cnt;j++)cout<<" ";
cout<<"*"<<endl;
}
for(j=0;j<pad;j++)cout<<" ";
cout<<"*"<<endl;
}
}
你可以摆脱变量i,怎么样?