为C++垂直上抛高度-时间计算程序添加抛射角功能的实现方案
斜抛参数扩展实现思路
核心原理调整
原有垂直上抛的高度公式结构无需修改,仅需把公式里的总初速度V替换为抛射运动的垂直方向有效初速度即可:
- 新增独立的抛射角输入项,用户输入的角度为日常使用的角度制(90度对应垂直上抛,完全兼容原有逻辑)
- C++
<cmath>库中的三角函数仅支持弧度制输入,因此必须先做单位转换:弧度值 = 角度值 * π / 180 - 垂直方向有效初速度计算公式:
垂直初速度 = 总初速度V * sin(弧度值) - 水平方向的速度分量仅影响水平射程,不参与高度计算,无需写入高度公式
代码改造步骤
- 头文件补充:引入
<cmath>,同时手动定义π常量(标准C++无内置M_PI,直接取近似值3.14159265358979323846即可) - 输入逻辑新增:增加抛射角的输入校验,限制输入范围为0~90度,超出范围判定为无效输入
- 公式替换:把原有计算行
Ht = -0.5 * G * Tt + V * i + H;中的速度项V*i替换为V * sin(angle_rad) * i - 场景对比适配:将抛射角设为90度的场景对应原垂直上抛逻辑,任意角度斜抛场景可直接与垂直上抛的输出结果做对比,直观呈现每秒高度损失的差异
原代码现存逻辑问题修复
- 原有循环
for (int i = 0; i < 10; i = i + S)硬编码了10秒的计算时长,物体提前落地后会被强制截断,建议改为无限循环,检测到高度小于0时自动break退出 - 原有冗余变量
T、Tt可直接在计算时声明使用,无需提前全局定义
改造后的核心代码片段
#include <iostream> #include <limits> #include <cmath> // 引入三角函数支持 using namespace std; const double PI = 3.14159265358979323846; int main() { const double G = 9.81; double H = 0; double V = 0; double launch_angle = 0; // 新增抛射角存储变量 double Ht = 0; int S; int s = 1; // 原有起始高度输入逻辑保持不变 cout << "\nGive me the starting height: "; while(!(cin >> H)){ cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "False input. Try again: "; } // 原有初速度输入逻辑保持不变 cout << "\nGive me the starting speed: "; while(!(cin >> V)){ cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "False input. Try again: "; } // 新增抛射角输入与校验 cout << "\nGive me the launch angle (0-90 degrees, 90 = vertical throw): "; while(!(cin >> launch_angle) || launch_angle <0 || launch_angle >90){ if(cin.fail()) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); } cout << "False input. Try again (angle must be 0 to 90): "; } // 角度转弧度 double angle_rad = launch_angle * PI / 180; // 原有显示间隔输入逻辑保持不变 cout << "\nHow often do you want the current height to be displayed (In seconds)\n"; while(!(cin >> S)){ cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "False input. Try again: "; } // 修复原循环逻辑,检测到落地自动退出 for (int i = 0; ; i += S) { double Tt = i*i; // 替换为垂直分量的高度计算公式 Ht = -0.5 * G * Tt + V * sin(angle_rad) * i + H; if (Ht >= 0){ cout << "Second " << s << " the height is " << Ht << " Meters" << endl; s += 1; } else { Ht = 0; cout << "Second " << s << " the height is " << Ht << " Meters" << endl; break; } } }
对比使用方法:分别用相同的起始高度、初速度,两次输入不同抛射角(一次90度,一次非垂直角度),对比两次输出的每秒高度值,即可得到斜抛与垂直上抛的高度损失差异。
内容的提问来源于stack exchange,提问作者whonnock
相关产品推荐
相关产品推荐

