蓝桥杯--小球反弹

    这道题完美融合了编程和物理模拟 一时兴起,写了这道题。感觉一些游戏的模拟设计应该也是同样的思路

题目描述:

        

思路:模拟一个坐标系,水平向右为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;
}

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值