注册 登录
编程论坛 C++教室

求助:C++循环和选择语句打印图形。

糖包包 发布于 2011-04-24 14:33, 2000 次点击
请问如何用C++循环和选择打印以下图形:

是:  *
    * *
   *   *
  *     *
   *   *
    * *
     *
程序代码:
#include <iostream>
using namespace std;
void main(void)
{
    int i,j;
    for(i=0;i<=3;i++)
    {for(j=0;j<=3+i;j++)
    if(j<3-i)cout<<" ";
    else cout<<"*";
    cout<<endl;}
    for(i=0;i<=2;i++)
    {for(j=0;j<=5-i;j++)
    if(j<=i)cout<<" ";
    else cout<<"*";
    cout<<endl;}

}
我自己写出来的怎么都调不好啊,显示出来是:
   *
  ***
 *****
*******
 *****
  ***
   *
我想用if语句把中间的去掉应该怎么写啊?T-T
5 回复
#2
lintaoyn2011-04-24 15:27
程序代码:
#include <iostream>
using namespace std;
void main(void)
{
    int i,j;
    for(i=0;i<=3;i++)//i是行。
    {
        for(j=0;j<=3+i;j++)
        {
            if(j==3-i || j==3+i)
                cout <<"*";
            else
                cout << " ";
        }
        cout<<endl;
    }
    for(i=0;i<=2;i++)
    {
        for(j=0;j<=5-i;j++)
        {
            if(j==i+1 || j ==5-i)
                cout << "*";
            else
                cout << " ";
        }
        cout<<endl;
    }
}
问题实际上是要求只打印每一行的左右两端的 * 。
通过你写的代码反推回去,得到第一次和最后一次进入else cout<<"*";时j的值。
if(j==3-i || j==3+i)
                cout <<"*";
其余的地方全部打上空格
#3
糖包包2011-04-24 21:33
回复 2楼 lintaoyn
!!青峰侠同学你太强了!!~~~

让我拜你为师吧~~
#4
糖包包2011-04-24 21:37
对哦,只用在他==3-i的时候出现*就行了~
我智商太低了。。。。。。
#5
linw12252011-04-25 22:39
回帖是一种美德。给楼主出个题目:
打印图案:

*   *   *
  *   *   *
    *   *   *
#6
玩出来的代码2011-04-25 23:16
写着玩。
程序代码:

#include<iostream>
#include<string>
using namespace std;

void Disply(int n,const string& str)
{
    cout<<string(n,' ')<<str<<endl;
}

void fun(string str,int n)
{
    if(n>1)
    {
        Disply(n,str);
        str.insert(1,2,' ');
        fun(str,n-1);
    }
    else
    {
        Disply(n,str);
        return ;
    }
    str.erase(1,2);
    Disply(n,str);
}

int main()
{
    string str="* *";
    int n=0;
    cin>>n;
    Disply(n,"*");
    fun(str,n-1);
    Disply(n,"*");

    //楼上这个不是更简单、、
    str="*   *   *";
    for(int i=0;i<n;i++)
    {
        cout<<string(i*2,' ')<<str<<endl;
    }
    return 0;
}

1