使用c绘制正弦波?

draw a sine wave using c?

#include <conio.h>
#include <math.h>
#include <graphics.h>
#include <dos.h>


int main() {

    int gd = DETECT, gm;

    int angle = 0;

    double x, y;

    initgraph(&gd, &gm, "C:\TC\BGI");


    line(0, getmaxy() / 2, getmaxx(), getmaxy() / 2);

    /* generate a sine wave */

    for(x = 0; x < getmaxx(); x+=3) {

        /* calculate y value given x */

        y = 50*sin(angle*3.141/180);

        y = getmaxy()/2 - y;

        /* color a pixel at the given position */

        putpixel(x, y, 15);

        delay(100);

        /* increment angle */

        angle+=5;

    }

    getch();

    /* deallocate memory allocated for graphics screen */

    closegraph();

    return 0;

}

这是程序。为什么我们要增加角度以及这个角度与图形有何关系?我把angle的值改为0,波浪就变成了一条直线。我想知道这个增量发生了什么。

Why are we incrementing the angle and how this angle is relevant to graph

sine function 以一个角度作为参数,通常是辐射角。该程序以度为单位实现角度,因此在传递给 sin().

的时刻它会被缩放为辐射点

正弦函数是周期性的(在之后重复)2*pi 或 360 度:

+---------+---------+------------+
|       angle       | sin(angle) |
+---------+---------+            |
| Radiant | Degrees |            |
+---------+---------+------------+
|       0 |       0 |          0 |
+---------+---------+------------+
|  1/2*pi |      90 |          1 |
+---------+---------+------------+
|      pi |     180 |          0 |
+---------+---------+------------+
|  3/2*pi |     270 |         -1 | 
+---------+---------+------------+
|    2*pi |     360 |          0 |
+---------+---------+------------+
|  5/2*pi |     450 |          1 |
+---------+---------+------------+
|    3*pi |     540 |          0 |
+---------+---------+------------+
|  7/2*pi |     630 |         -1 | 
+---------+---------+------------+
|    4*pi |     720 |          0 |
+---------+---------+------------+
|     ... |     ... |        ... |

and so on ...

changed the value of angle to 0 and the wave became a straight line

sin(0)的结果是0

For the mathematical derivation you might like to have a look here.