2016-12-06 144 views
1

我已經讀了this,我試圖用C++來實現它,但輸出是完全不同的。我不知道什麼是錯的。 我使用的代碼:將圓劃分成n等分來得到每個劃分點的座標

double cordinate_print() 
{ 
    int x, y; 
    int number_of_chunks = 5; 
    double angle=0; 
    double x_p[5] ; // number of chunks 
    double y_p[5]; // number of chunks 
    //double x0, y0 = radious; 
    double rad = 150; 

    for (int i = 0; i < number_of_chunks; i++) 
    { 
     angle = i * (360/number_of_chunks); 
     float degree = (angle * 180/M_PI); 
     x_p[i] = 0 + rad * cos(degree); 
     y_p[i] = 0 + rad * sin(degree); 
     //printf("x-> %d y-> %d \n", x_p[i], y_p[i]); 
     cout << "x -> " << x_p[i] << "y -> " << y_p[i] << "\n"; 
    } 

    //printing x and y values 

    printf("\n \n"); 

    return 0; 

} 

輸出

x -> 150 y -> 0 
x -> -139.034 y -> -56.2983 
x -> 107.74 y -> 104.365 
x -> -60.559 y -> -137.232 
x -> 4.77208 y -> 149.924 

正確輸出

(150,0) 

(46,142) 

(-121,88) 

(-121,-88) 

(46,-142) 
+0

調用變量「度數」時,實際上以弧度表示的角度會誤導人類。不過,編譯器並不在乎。不要直接看到問題,但點確實出現在圓上 - 這只是角度錯誤。 – MSalters

回答

1

問題與度轉化爲弧度

float degree = (angle * 180/M_PI); 

正確conversi上的公式是

float radian = (angle * M_PI/180); 

也正如在評論中提到的使用良好的名稱,以避免任何混淆。

+0

@非常感謝你 – Alan

1

由於您的默認角度是度數,因此您需要先使用sin()cos()將它們轉換爲弧度,然後再將其乘以半徑。

double cordinate_print() 
{ 
    int number_of_chunks = 5; 
    double degrees = 0;       // <-- correction 
    double x_p[5]; // number of chunks 
    double y_p[5]; // number of chunks 
    double radius = 150;      // <-- correction 

    for (int i = 0; i < number_of_chunks; i++) 
    { 
     degrees = i * (360/number_of_chunks); // <-- correction 
     float radian = (degrees * (M_PI/180)); // <-- correction 
     x_p[i] = radius * cos(radian);   // <-- correction 
     y_p[i] = radius * sin(radian);   // <-- correction 

     cout << "x -> " << x_p[i] << "y -> " << y_p[i] << "\n"; 
    } 

    //printing x and y values 
    printf("\n \n"); 

    return 0; 
} 
+0

非常感謝。 – Alan