如何用语法表示动力学方程
How to represent the kinetic equation in syntax
所以我想写这个公式
KE = 1 / 2mv^2
c++中的,创建一个使用动能方程计算值的函数。但我不完全是确定如何显示1 / 2
。我不需要把它写成double
吗因为如果我把1 / 2
表示成一个整数它就会显示5
?编译器真正看到的将是0.5
,从零被切断?这里是我到目前为止计算这个方程的代码:double KE = 1/2*mvpow(KE,2);这是我的代码和我要做的。
当我使用2
和5
的测试值时,它给我0
而不是25
。
//my protyped function kineticEnergy
double kineticEnergy(int m, int v);
int main(){
int m; // needed to pass a value into kineticEnergy function
int v; // needed to pass a value into kineticEnergy function
cout << "Enter the mass " << endl;
cin >> m;
cout << "Enter the velocity" << endl;
cin >> v;
int results = kineticEnergy(m,v);
cout << "The total kinetic energy of the object is " << results << endl;
return 0;
} // end of main
// ##########################################################
//
// Function name: kineticEnergy
//
// Description:This will grab input from a program and calculate
// kinetic energy within the function
// ##########################################################
double kineticEnergy(int m, int v){
double KE = 1/2*m*v*pow(KE,2); // equation for calculating kinetic energy
return KE;
} // end of kinetic energy
使用std::array<double,3>
作为速度矢量:
double kinetic_energy(double mass, std::array<double,3> const&velocity)
{
return 0.5 * mass * (velocity[0]*velocity[0]+
velocity[1]*velocity[1]+
velocity[2]*velocity[2]);
}
注意1)速度是一个矢量(其大小是速度),2)不建议使用std::pow()
计算平方:它比单个乘法(使用c++ 11)计算成本高得多。你可以使用辅助的
inline double square(double x)
{ return x*x; }
和
double kinetic_energy(double mass, std::array<double,3> const&velocity)
{
return 0.5 * mass * (square(velocity[0])+square(velocity[1])+square(velocity[2]));
}
是的,1和2是整数常量,所以1/2
给出0
,它是1除以2的整数除法的结果。
你想要的是这个(假设" m*v*pow(KE,2)
"是正确的):
double KE = 1.0/2.0*m*v*pow(KE,2);
最好的办法是-
我花了4个小时来设计、修改和简化这个答案。
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int m;
cout << "Enter mass (in kg): ";
cin >> m;
int v;
cout << "Enter velocity (in m/s): ";
cin >> v;
cout << "If mass is " << m << " kg" << endl;
cout << "and velocity is " << v << " m/s," << endl;
float kinEn = m * pow(v,2) * (0.5);
cout << "then kinetic energy is " << kinEn << " Joules" << endl;
return 0;
}
避免使其成为函数并且大多数尝试先声明,然后写它是关于什么的(使用cout),然后为输入值提供空间(使用cin)。
代码给出如下结果:
Enter mass (in kg):
Enter velocity (in m/s):
If mass is 57 kg
and velocity is 20 m/s,
then kinetic energy is 11400 Joules
相关文章:
- 正弦级数方程计算不正确
- 线性丢番图方程 - 求给定区间内的解数和解
- 这个方程 x + y = x & y + x |y 成立(假设 x, y > 0)?
- 尝试创建包含简单方程的函数
- 我正在尝试根据 4 个方程找出六个值
- 在 // C++注释中使用 \\ 是否合法?(C++评论中的LaTeX方程)
- 我正在尝试在 C++ 中做一个方程,但它一直输出 1
- 查找满足浮点不等式方程的最小整数
- 用蛮力解方程
- 给定方程 : x = (((x+8)/3)%5)*5;使用赋值运算符求解上述方程(例如 +=, -=, *=)
- 为什么同一个逻辑方程在python和c++中返回两个不同的结果
- 如何在ROS中使用PCL可视化动力学数据的表面法线
- C++ 在方程中使用变量;错误:表达式必须具有整数或无作用域枚举类型及其他
- C++ 递减和显示活动方程
- 项目符号 3 动力学不适用于非球体
- 在C++中使用RK-4求解洛伦兹方程
- 如何从用户那里获取方程的输入并在 c++ 中对其进行评估
- 如何使用OpenACC集成微分方程
- C++四元数方程程序
- 如何用语法表示动力学方程