回 帖 发 新 帖 刷新版面

主题:C++ 输入一个奇数得到一个菱形

#include<iostream>
using namespace std;
int main()
{
    int suru=0,shang=0,xia=0,a=0,b=0,c=0,d=0;
    cout<<"请输入一个奇数:";
    cin>>suru;
    if(suru%2 == 1)
    {
            d=suru-(suru-1);
            c=suru/2;
            while(shang == 0)
            {
                for(;b<d && d<suru;b++)
                {
                    for(;a<c;a++)
                    {
                        cout<<" ";
                    }
                    cout<<"*";
                }
                if(b==d)
                {
                cout<<endl;
                }
                a=0,c--,b=0,d+=2;
                if(d>suru)
                {
                    a=0,b=0,c=0,d=suru;
                    while(xia==0)
                    {
                        for(;a<d;a++)
                        {
                            for(;b<c;b++)
                            {
                                cout<<" ";
                            }
                            cout<<"*";
                        }
                        cout<<endl;
                        b=0,c++,a=0,d-=2;
                        if(d<a)
                        {
                            shang=1;
                            xia=1;
                        }
                    }
                }
            }
    }
else if(suru%2 == 0)
            {
                cout<<"你输入的不是一个数字或者这个数字不是奇数!!";
            }
return 0;
}
这个是我写的  VC6.0 通过   我是一个新手   想请高手们看看  还有什么更好的方法实现! 主要想知道下算法帮我改进下我的代码  谢谢!

回复列表 (共1个回复)

沙发

#include<iostream>
using namespace std;
int main()
{
    int suru=0,i,j;
    cout<<"请输入一个奇数:";
    cin>>suru;
    if(suru%2 == 1)
    {
            for (i=0;i<suru;i++)
            {
                for(j=1;j<abs((suru-1)/2-i)+1;j++)
                {
                    cout<<" ";
                }
                for(j=1;j<((suru+1)/2-abs((suru-1)/2-i))*2;j++)
                {
                    cout<<"*";
                }
                cout<<endl;
            }

    }
else if(suru%2 == 0)
            {
                cout<<"你输入的不是一个数字或者这个数字不是奇数!!";
            }
return 0;
}

新浪微博: 李思扬_pa

我来回复

您尚未登录,请登录后再回复。点此登录或注册