Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Chương trình C tìm cos và sin dùng thư viện math.h


Vấn đề

Tìm giá trị cos và sin cho mỗi 10 độ từ 0 đến 150.

Giải pháp

Logic tìm giá trị cos:

Khai báo MAX và PI đầu chương trình

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

Logic tìm giá trị sin:

Khai báo MAX và PI.

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

Ví dụ 1: Cos

Chương trình C tìm giá trị cos:

// cos values 
#include <stdio.h> 
#include <math.h> 
#define PI 3.1416 
#define MAX 150 
main(){ 
    int angle; 
    float x, y; 
    angle = 0; 
    printf("Goc cos(goc)\n\n"); 
    while(angle <= MAX){ 
        x = (PI/MAX) * angle; 
        y = cos(x); 
        printf("%15d %13.4f\n", angle, y); 
        angle += 10; 
    } 
}

Đầu ra Cos

Goc cos(goc) 
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

Ví dụ 2: Sin

Chương trình C tìm giá trị sin:

// sin values 
#include <stdio.h> 
#include <math.h> 
#define PI 3.1416 
#define MAX 150 
main(){ 
    int angle; 
    float x, y; 
    angle = 0; 
    printf("Goc sin(goc)\n\n"); 
    while(angle <= MAX){ 
        x = (PI/MAX) * angle; 
        y = sin(x); 
        printf("%15d %13.4f\n", angle, y); 
        angle += 10; 
    } 
}

Đầu ra Sin

Goc sin(goc) 
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