1.所需头文件
#include <math.h>
2.使用方法
输入double类型参数,并返回double类型
注意:输入参数应为弧度制(radians),而不是角度制(degrees)
2_1.弧度制与角度制的转换
弧度制几何意义:弧度rad = 圆弧长度l ÷ 半径r,表示了在圆上移动l距离对应的角度。
常见的 = 3.1415926...便是弧度,一弧度 = 180°/ 角度
转换:deg = 180°/ * rad red = / 180° * deg
deg: 角度 rad : 弧度
3.示例
3_1.代码展示
在编写简单的小游戏 “见缝插针” 中,sin()、cos()函数便作为核心。
#define _CRT_SECURE_NO_WARNINGS
#include <math.h>
#include <easyx.h>
#include <stdio.h>
#define width 500
#define height 500
void Launch(ExMessage* msg, float Arg[], int* num, int* score)//发射函数
{
if (peekmessage(msg, EM_MOUSE))
{
if (msg->lbutton)
{
Arg[*num] = 0;
(*num)++;
(*score)++;
Sleep(10);//按键消抖,防止按一下插入多根针
}
}
}
int Lose(float Arg[], int* num)//失败函数
{
if (*num > 1)
{
for (int i = 0; i < (*num) - 1; i++)
{
if (Arg[i] <= Arg[(*num) - 1] + 2 && Arg[i] >= Arg[(*num) - 1] - 2)
{
return 0;
}
}
}
return 1;
}
void Draw()//画图函数
{
setlinecolor(RGB(255, 155, 65));
setfillcolor(YELLOW);
fillcircle(width / 2, height / 2, 50);
setfillcolor(RGB(255, 155, 65));
solidellipse(width / 2 - 20, height / 2 - 20, width / 2 - 10, height / 2);
solidellipse(width / 2 + 10, height / 2 - 20, width / 2 + 20, height / 2);
solidpie(width / 2 - 30, height / 2 - 10, width / 2 + 30, height / 2 + 30, 3.1415926, 0);
}
void Scoreboard(int* score)//计分板函数
{
char str[4];
settextcolor(RED);
settextstyle(40, 0, "Bradley Hand ITC");
sprintf(str, "%d", * score);
outtextxy(10, 10, "SCORE:");
outtextxy(10, 50, str);
}
void Fail(int* score, int* flag)//结束函数
{
BeginBatchDraw();
setbkcolor(WHITE);
setbkmode(TRANSPARENT);
cleardevice();
char str[4];
char str1[] = "your score:";
int wid = textwidth(str1);
int hei = textheight(str1);
settextcolor(RED);
settextstyle(40, 0, "Bradley Hand ITC");
sprintf(str, "%d", *score);
int wid_s = textwidth(str);
int hei_s = textheight(str);
outtextxy((width - wid) / 2, (height - hei) / 2 - 50, str1);
outtextxy((width - wid_s) / 2, (height - hei_s) / 2, str);
EndBatchDraw();
*flag = 1;
Sleep(3000);
}
int main()
{
while (1)
{
int flag = 1;
int num = 0;//定义当前针的个数
int score = 0;//定义分数
float pi = 3.1415926;
float Arg[100] = { 0 };//定义角度数组,最多放100根针
float rad = 0;//定义弧度
int len = 120;//定义线的长度
int intx, inty;//定义线的起始坐标
int endx, endy;//定义线的末尾坐标
ExMessage msg;
initgraph(width, height);
while (flag)
{
BeginBatchDraw();
setbkcolor(RGB(174, 225, 238));
cleardevice();
setlinestyle(PS_SOLID, 8);
setlinecolor(RED);
line(width - 100, height / 2, width, height / 2);//发射区线条格式设置
setlinestyle(PS_SOLID, 4);
Launch(&msg, Arg, &num, &score);
flag = Lose(Arg, &num);
for (int i = 0; i < num; i++)
{
Arg[i]++;
if (Arg[i] == 360)
{
Arg[i] = 0;
}
rad = pi / 180 * Arg[i];//角度转弧度
intx = 60 * cos(rad) + width / 2;//起始坐标随角度变化而变化
inty = 60 * sin(rad) + height / 2;
endx = len * cos(rad) + width / 2;//尾部坐标随角度变化而变化
endy = len * sin(rad) + height / 2;
if (i < num - 1)
{
setlinecolor(RGB(255, 155, 65));
}
else
{
setlinecolor(RED);
}
line(intx, inty, endx, endy);
}
Draw();
Scoreboard(&score);
EndBatchDraw();
Sleep(1);
}
Sleep(500);
Fail(&score, &flag);
}
getchar();
return 0;
}
3_2.效果展示图