繁体   English   中英

在C ++中画一个圆,但画一个菱形

[英]Drawing a circle in C++, but drawing a diamond instead

我正在做一个编码项目,使我们可以使用星号绘制各种形状。 到目前为止,我已经绘制了一个X,一个矩形以及一个正方形的上下部分。 最终项目使我们绘制了一个圆,并且使用了与之前四个项目相同的方法-使用嵌套的for和if else循环创建一种排序网格,并指定在何处绘制“”或“ *”不足。 这是我的代码:

int main() { 

int rad; // int for radius


cout << "We are creating a circle made of asterisks. Please input the radius: " << endl;
cin >> rad;

int i; 
int t;


for(i = 1 ; i <= (rad * 2) + 1; i++) 
{
    for(t = 1; t <= (rad * 2) + 1 ; t++) 
    {
        if((i == 1 && t == rad + 1) /*|| (i  == (rad * 2) && t == rad + 1) || (i == rad/2 && t == rad/2)*/) 
        {
            cout << "*";
        }
        else if (i >= 2 && i <= rad && t == (rad+1) - (i-1))
        {
            cout << "*";
        }
        else if (i >= 2 && i <= rad && t == (rad+1) + (i-1))
        {
            cout << "*";
        }
        else if (i >= rad && t == (i - rad))
        {
            cout << "*";
        }
        else if (i >= rad && t == (rad * 2) + 2 - (i - rad))
        {
            cout << "*";
        }
        else 
        {   
            cout << " ";
        }
    }
    cout<< endl;
}
return 0;
}

上面的输出? 完美的钻石:

    We are creating a circle made of asterisks. Please input the radius: 5

     *     
    * *    
   *   *   
  *     *  
 *       * 
*         *
 *       * 
  *     *  
   *   *   
    * *    
     *  

显然我的方法不起作用。 我尝试调整参数以增加星号的间距,从而创建一种近似的圆,但看起来并不正确。 我不禁要想到必须有一种优雅而优越的方法。 也许是使用半径的更数学方法。 有什么建议或提示吗?

这是一种使用半径绘制圆的更数学的方法。

#include <iostream>
#include <math.h>

using namespace std;

int pth (int x,int y)  {
    return sqrt (pow(x,2)+pow(y,2));
 }

int main ( )  {

    int c=0;
    int r=10;

    const int width=r;
    const int length=r*1.5;

    for (int y=width;y >= -width;y-=2)  {
        for (int x=-length;x <= length;x++)  {

            if ((int) pth(x,y)==r) cout << "*";
            else cout << " ";

         }
         cout << "\n";
     }
     cin.get();

return 0;
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM