我正在尝试计算方程式描述的速度的时程: dV / dt = g −(C_d / m)* V ^ 2 。 g = 9.81,m = 1.0,C_d = 1.5。 为此,我需要在c ++中创建一个程序,该程序使用Euler显式方法对方程进行数值求解。我试图以三种不同的步长delta_t = 0.05、0.1和0.2秒找到从t = 0到t = 1秒的速度。然后,您应该按照以下公式显示分析解决方案的百分比误差: V(t)= sqrt((m * g)/ C_d)* tanh(sqrt((g * C_d)/ m)* t )。 我的问题是我不确定如何在不同的时间间隔内多次遍历欧拉方法。到目前为止,我已经解决了解析方程,但是不确定从这里开始。如果有人能帮助我指出正确的方向,将不胜感激。
#include <iomanip>
#include <cmath>
#include <math.h>
using namespace std;
int main() {
double m = 1.0; // units in [kg]
double g = 9.81; // units in [m/s^2]
double C_d = 1.5; // units in [kg/m]
double t; // units in [s]
double v; // units in [m/s]
cout << "The velocity will be examined from the time t = 0 to t = 1 seconds." << endl;
cout << "Please select either 0.05, 0.1, or 0.2 to be the time interval:" << endl;
cin >> t;
cout << "You have chosen the time interval of: " << t << " seconds." << endl;
v = sqrt((m * g) / C_d) * tanh(sqrt((g * C_d) / m) * t);
cout << "The velecity at a time of "<< t << " seconds is equal to: " << v << " m/s." << endl;
return 0;
} ```
答案 0 :(得分:1)
如果要以 A 的增量迭代 t ,并用每个 t 计算公式的结果,则可以编写一个for循环。
#include <iostream>
int main()
{
double m = 1.0; // units in [kg]
double g = 9.81; // units in [m/s^2]
double C_d = 1.5; // units in [kg/m]
std::cout << "The velocity will be examined from the time t = 0 to t = 1 seconds." << std::endl;
std::cout << "Please select the time interval:" << std::endl;
std::cout << "1: 0.05" << std::endl;
std::cout << "2: 0.1" << std::endl;
std::cout << "3: 0.2" << std::endl;
double A = 0; // increment in for loop
int x;
std::cin >> x;
switch (x) { // check what the input is equal to
case 1: A = 0.05; break;
case 2: A = 0.1; break;
case 3: A = 0.2; break;
default: std::cout << "Unknown option!" << std::endl; return 1;
}
std::cout << "You have chosen the time interval of: " << A << " seconds." << std::endl;
std::cout << "Results of V(t):" << std::endl;
// this initializes a variable t as 0,
//and while t is lower than or equal to 1,
//it will increment it by a and execute the logic within the scope of the loop.
for (double t = 0; t < (1 + A); t += A) {
std::cout << "at t = " << t << ": " << sqrt((m*g) / C_d) * tanh(sqrt((g*C_d) / m) * t) << std::endl;
}
return 0;
}
有关更多信息,请参见https://beginnersbook.com/2017/08/cpp-for-loop/。注意:我还在代码中引入了switch语句,以防止输入未知值。 https://beginnersbook.com/2017/08/cpp-switch-case/