这道题完美融合了编程和物理模拟 一时兴起,写了这道题。感觉一些游戏的模拟设计应该也是同样的思路
题目描述:
思路:模拟一个坐标系,水平向右为x正方向 竖直向下为y的正方向。我们只需要写出状态判断逻辑,并让每个单位时间内的ds(一小段位移)去进行累加
代码:
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
int main() {
const int maxX = 343720;
const int maxY = 233333;
const int vx = 15;
const int vy = 17;
int x = 0, y = 0;
int time = 0;
double totalDistance = 0;
bool xPositive = true, yPositive = true;
while (true) {
x += xPositive ? vx : -vx;
y += yPositive ? vy : -vy;
time++;
double segmentLength = sqrt(vx * vx+ vy * vy);
// 检查是否碰到边界并反弹
if (x > maxX || x < 0) {
xPositive = !xPositive; // 反转X方向
x = (x > maxX) ? maxX : 0; // 将坐标调整到边界上
}
if (y > maxY || y < 0) {
yPositive = !yPositive; // 反转Y方向
y = (y > maxY) ? maxY : 0; // 将坐标调整到边界上
}
// 累加路径长度
totalDistance += segmentLength;
// 假设当粒子回到原点时停止模拟
if (x == 0 && y == 0) {
break;
}
}
// 输出总路径长度
cout << "总路径为:" << totalDistance << endl;
return 0;
}