如何用语法表示动力学方程

How to represent the kinetic equation in syntax

本文关键字:动力学 方程 表示 语法 何用      更新时间:2023-10-16

所以我想写这个公式

KE = 1 / 2mv^2
c++中的

,创建一个使用动能方程计算值的函数。但我不完全是确定如何显示1 / 2。我不需要把它写成double吗因为如果我把1 / 2表示成一个整数它就会显示5 ?编译器真正看到的将是0.5,从零被切断?这里是我到目前为止计算这个方程的代码:double KE = 1/2*mvpow(KE,2);这是我的代码和我要做的。

当我使用25的测试值时,它给我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