在C++画一个圆,但画一个钻石

Drawing a circle in C++, but drawing a diamond instead

本文关键字:一个 钻石 C++      更新时间:2023-10-16

我正在做一个编码项目,让我们用星号绘制各种形状。到目前为止,我已经画了一个X,一个矩形,以及一个正方形的上半部分和下半部分。最后一个项目让我们画一个圆,而我在前 4 个项目中一直使用的方法相同 - 使用嵌套的 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;
 }

这里有一些关于如何画圆的提示:

  • http://www.tutorialspoint.com/computer_graphics/circle_generation_algorithm.htm
  • https://en.wikipedia.org/wiki/Midpoint_circle_algorithm