Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C หาค่า cosine และ sine ด้วยไลบรารี math.h

ปัญหา

หาค่า cosine และ sine สำหรับทุก 10 องศา จาก 0 ถึง 150 องศา

วิธีแก้ปัญหา

ค่า Cosine

ประกาศค่า MAX และ PI เริ่มต้นโปรแกรม

while(angle <= MAX) {
    x = (PI/MAX)*angle;
    y = cos(x);
    printf("%15d %13.4f\n", angle, y);
    angle = angle + 10;
}

ค่า Sine

ประกาศค่า MAX และ PI เริ่มต้นโปรแกรม

while(angle <= MAX) {
    x = (PI/MAX)*angle;
    y = sin(x);
    printf("%15d %13.4f\n", angle, y);
    angle = angle + 10;
}

ตัวอย่างโค้ด Cosine

// cosine values
#include <stdio.h>
#include <math.h>
#define PI 3.1416
#define MAX 150

int main() {
    int angle;
    float x, y;
    angle = 0;
    printf("Angle cos(angle)\n\n");
    while(angle <= MAX) {
        x = (PI/MAX)*angle;
        y = cos(x);
        printf("%15d %13.4f\n", angle, y);
        angle = angle + 10;
    }
    return 0;
}

ผลลัพธ์ Cosine

Angle cos(angle)
             0     1.0000
            10     0.9781
            20     0.9135
            30     0.8090
            40     0.6691
            50     0.5000
            60     0.3090
            70     0.1045
            80    -0.1045
            90    -0.3090
           100    -0.5000
           110    -0.6691
           120    -0.8090
           130    -0.9135
           140    -0.9781
           150    -1.0000

ตัวอย่างโค้ด Sine

// sine values
#include <stdio.h>
#include <math.h>
#define PI 3.1416
#define MAX 150

int main() {
    int angle;
    float x, y;
    angle = 0;
    printf("Angle sin(angle)\n\n");
    while(angle <= MAX) {
        x = (PI/MAX)*angle;
        y = sin(x);
        printf("%15d %13.4f\n", angle, y);
        angle = angle + 10;
    }
    return 0;
}

ผลลัพธ์ Sine

Angle sin(angle)
             0     0.0000
            10     0.2079
            20     0.4067
            30     0.5878
            40     0.7431
            50     0.8660
            60     0.9511
            70     0.9945
            80     0.9945
            90     0.9511
           100     0.8660
           110     0.7431
           120     0.5878
           130     0.4067
           140     0.2079
           150    -0.0000