2016-02-21 111 views
0

我正在編寫一個編碼項目,讓我們使用星號繪製各種形狀。到目前爲止,我繪製了一個X,一個矩形,以及一個正方形的上部和下部。最後的項目讓我們畫了一個圓圈,並使用了以前4個項目的相同方法 - 使用嵌套for和if循環創建一種網格,並指定在哪裏繪製「」或「 *「不足。這裏是我的代碼:在C++中繪製一個圓,但是繪製菱形代替

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 

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

顯然我的方法不起作用。我試着調整我的參數來增加星號的間距,創建一種粗略的圓圈近似,但它看起來不正確。我不禁想到要做到這一點,必須有一種優雅,高級的方式。也許更多的數學方法使用半徑。任何建議或提示?

+1

如何繪製不使用幾何圖形的圓? – stark

+2

是什麼讓一個圓的點...圓,是這樣的:**(x-cx)^ 2 +(y-cy)^ 2 = r^2 **。你有一個不合理的條件。 –

+0

你可以看看這個:[Visit this](http://stackoverflow.com/questions/24356723/how-to-draw-a-circle-with-asterisk-function-in-ruby) –

回答

1

下面是一個使用半徑畫圓更數學方法。

#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; 
}