JS与C++表达式评估

JS vs C++ expression evaluation

本文关键字:评估 表达式 C++ JS      更新时间:2023-09-26

我必须将一些算法从JavaScript重写为C++。所以我有一个问题:我应该注意什么?在 JS 和C++中评估有什么区别?

例如,此缓动算法:

var pi2 = Math.PI * 2;
var s = period/pi2 * Math.asin(1/amplitude);
if ((t*=2)<1) return -0.5*(amplitude*Math.pow(2,10*(t-=1))*Math.sin( (t-s)*pi2/period ));
return amplitude*Math.pow(2,-10*(t-=1))*Math.sin((t-s)*pi2/period)*0.5+1;

当我简单地将 var s 更改为 double s 并将 Math. 更改为 std:: 时,它将编译,但表达式中的-=会导致 UB(我的编译器说)。

您还知道哪些其他棘手的差异?

JavaScript

和 C++ 非常无可比性。就像苹果和橙子一样。两者都是可以执行计算/函数的语言(就像苹果和橙子都是水果一样),但它们几乎没有相似之处。

这大致是 JavaScript 代码的C++实现:

#include <iostream>
#include <math.h>
using namespace std;
const double PI = 3.141592653589793;
const double twoPI = PI * 2;
int main(int argc, char *argv[]){
    /*
     * I do not know what t is supposed to be, so I
     * randomly chose a value.
     */
    double t = 0.43;
    double amplitude = 1.0;
    double period = 2.0;
    /* I have filled in some standard values for period
       and amplitude because your code did not supply any. */
    double s = (period/twoPI) * asin(1/amplitude);
    if( (t*2) < 1){
        double exponentForPow = 10.0*(t-1);
        double powPiece = amplitude * pow(2.0, exponentForPow);
        double sinPiece = sin(((t-s) * (twoPI/period)));
        double finalAnswer = (-0.5 * powPiece * sinPiece);
        cout << finalAnswer << endl;
    }else{
        double exponentForPow = -10.0*(t-1);
        double powPiece = amplitude * pow(2, exponentForPow);
        double sinPiece = sin(((t-s) * (twoPI/period)));
        double finalAnswer = 1.0 + (0.5*( powPiece * sinPiece ));
        cout << finalAnswer << endl;
    }
    return 0;
    // in C++, the main() function must an integer.
    // You could return finalAnswer if you wrote a
    // second function just for the calculation
}

我没有测试过这段代码,所以我不知道它是否能正确编译,或者它是否会产生想要的结果。但是,它应该为您提供一个很好的概述,或者至少对您发布的代码如何用C++编写有一个很好的了解。