我也国庆大赠送,新手尝试一下:猎狗追兔
一只兔子在离窝D处,一只猎狗在兔子与窝连线的垂直距离L处、且正对兔子(即三点连成直角)。猎狗发现兔子,以恒定速度大小v向兔子扑去,与此同时,兔子也以速度u逃往自己的窝。假设猎狗始终面向兔子追赶,试问它能逮到兔子吗?程序要求:自己输入D、L、v、u,算出结果。
扩展:
1.猎狗位置可随意;
2.动画模拟过程。
程序代码:
#include <locale.h>
#include <stdio.h>
#include <math.h>
#include <conio.h>
// 坐标点结构
typedef struct Coord
{
double x; // x 坐标
double y; // y 坐标
};
const wint_t K_ENTER = 0x000D;
const double D_Distance = 50.0; // 兔子离窝的距离
const double L_Distance = 100.0; // 猎狗离兔子的距离
const double v_Speed = 5.0; // 兔子的速率
const double u_Speed = 12.1; // 猎狗的速率
const double tininess = 0.0001; // 时间微小增量
void pause(void);
void main(void)
{
Coord rabbit = {0.0, 0.0}; // 兔子位置
Coord hound = {0.0, -L_Distance}; // 猎狗位置
double angle; // 猎狗的方向角
bool success = false;
setlocale(LC_ALL, "chs"); // 设定语言为中文输出
wprintf_s(L"兔子位置(%.2lf%c%.2lf)\n", rabbit.x, ',', rabbit.y);
wprintf_s(L"兔子窝位置(%.2lf%c%.2lf)\n", D_Distance, ',', 0.0);
wprintf_s(L"猎狗位置(%.2lf%c%.2lf)\n\n", hound.x, ',', hound.y);
wprintf_s(L"兔子速率%.2lfm/s\n", v_Speed);
wprintf_s(L"猎狗速率%.2lfm/s\n\n", u_Speed);
while ((rabbit.x < D_Distance) && !success)
{
rabbit.x += v_Speed * tininess; // 兔子运动
angle = atan((rabbit.x - hound.x) / (0.0 - hound.y)); // 猎狗与兔子连线对y轴的夹角
hound.x += u_Speed * sin(angle) * tininess; // 猎狗在x轴方向的运动
hound.y += u_Speed * cos(angle) * tininess; // 猎狗在y轴方向的运动
if (hound.y >= 0.0) // 一旦猎狗超越x轴即逮着兔子,与hound.x >= rabbit.x等价
{
wprintf_s(L"猎狗在离窝边%.2lf处逮到兔子了!\n", D_Distance - rabbit.x);
success = true;
}
}
if (!success)
{
wprintf_s(L"兔子成功逃脱!\n");
}
pause();
}
void pause(void)
{
wint_t character;
wprintf_s(L"\n====按Enter键结束====");
do
{
character = _getwch();
} while (character != K_ENTER);
}
