2011-04-20 16 views

回答

5

這是一個很長的時間,因爲我已經做了C/C++,所以我已經在這個多刺,看看我是如何得到的呢,但這裏的一些代碼,將計算點爲你。 (這是一個VS2010控制檯應用程序)

// CirclePoints.cpp : Defines the entry point for the console application. 
// 

#include "stdafx.h" 
#include "stdio.h" 
#include "math.h" 

int _tmain() 
{ 
    int points = 8; 
    double radius = 100; 

    double step = ((3.14159265 * 2)/points); 
    double x, y, current = 0; 
    for (int i = 0; i < points; i++) 
    { 
     x = sin(current) * radius; 
     y = cos(current) * radius; 

     printf("point: %d x:%lf y:%lf\n", i, x, y); 

     current += step; 
    } 

    return 0; 
} 
+1

我選擇這個作爲接受的答案,因爲你向我展示瞭如何得到我和我的項目所需要的x和y點。我可以解釋一下數學嗎?我只有13歲,所以請儘量保持你的解釋儘可能簡單。 – 2011-05-07 23:43:26

5

嘗試是這樣的:

void make_circle(float *output, size_t num, float radius) 
{ 
    size_t i; 

    for(i = 0; i < num; i++) 
    { 
    const float angle = 2 * M_PI * i/num; 
    *output++ = radius * cos(angle); 
    *output++ = radius * sin(angle); 
    } 
} 

這是未經測試,有可能是關閉的情況,一個隱藏在角度步長計算,但它應該接近。

這是假設我理解正確的問題,當然。

UPDATE:重新計算角度計算不增加,以減少重複加法造成的浮點精度損失。

+0

重複添加會導致錯誤累積 - 您最好在循環中使用'angle = i * 2 * M_PI/num;'。 – caf 2011-04-20 12:58:18

+1

或者,如果你不關心小錯誤積累,你可以通過計算'cos'和'sin'一次,然後循環獲取複數值cos(角度)+ i * sin(角度)'。這將會**這麼快**。 – 2011-04-20 13:01:15

+0

@caf:好點,固定。 – unwind 2011-04-20 13:02:20

0

你必須用C語言來解決這個:

在XY笛卡爾座標系,具有中心的圓座標(a,b)和半徑r爲集合中的所有點(X,Y),使得

(X - A)^ 2 +(Y - b)^ 2 = R^2

+0

看起來像標籤作業,這就是爲什麼我不想寫代碼.... – 2011-04-20 12:59:49

+1

這就是爲什麼我寫了奇特的解決方案和挑戰的OP解釋給他們的教授,如果他們逐字複製它; ;-) – 2011-04-20 13:10:03

2

這裏的一個解決方案,有些優化,未經測試。錯誤可能會累積,但使用double而不是float可能會超過它,除非有極大值n

void make_circle(double *dest, size_t n, double r) 
{ 
    double x0 = cos(2*M_PI/n), y0 = sin(2*M_PI/n), x=x0, y=y0, tmp; 
    for (;;) { 
     *dest++ = r*x; 
     *dest++ = r*y; 
     if (!--n) break; 
     tmp = x*x0 - y*y0; 
     y = x*y0 + y*x0; 
     x = tmp; 
    } 
} 
+0

要真正挑剔,對於大n,你將失去一點準確性,通過更新x和y這種方式,因爲x0將接近於1.通過使用d0 = cos(2pi/n)-1 = -2 * sin (pi/n)* sin(pi/n),然後更新爲tmp = x * d0-y * y0; y + = x * d0 + y * x0; x + = tmp; – dmuir 2011-04-21 10:57:36

+0

爲了公平起見,我說你會爲大'n'積累錯誤,但是感謝你的改進。 :-) – 2011-04-21 12:16:40

0

這是一個JavaScript實現,它也需要一個可選中心點。

function circlePoints (radius, numPoints, centerX, centerY) { 
    centerX = centerX || 0; 
    centerY = centerY || 0; 

    var 
    step = (Math.PI * 2)/numPoints, 
    current = 0, 
    i = 0, 
    results = [], 
    x, y; 

    for (; i < numPoints; i += 1) { 
    x = centerX + Math.sin(current) * radius; 
    y = centerY + Math.cos(current) * radius; 

    results.push([x,y]); 

    console.log('point %d @ x:%d, y:%d', i, x, y); 

    current += step; 
    } 

    return results; 
} 
+0

嗨,歡迎來到Stack Overflow。雖然這應該是微不足道的轉化爲C,請在將來的答案中堅持標籤。這是一個C語言問題,應該給予C-答案。 – user13500 2014-03-04 02:01:39

相關問題