将圆分成n个相等的部分以获得每个分界点的坐标

时间:2016-12-06 07:13:41

标签: c++

我已阅读this并尝试在C ++中实现它,但输出完全不同。我不知道出了什么问题。 我使用的代码:

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)

2 个答案:

答案 0 :(得分:1)

将度数转换为弧度

的问题
float degree = (angle * 180 / M_PI);

正确的转换公式是

float radian = (angle * M_PI / 180);

同样如评论中所述,使用好名称以避免任何混淆。

答案 1 :(得分: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;
}