2016-12-06 149 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