JS与C++表达式评估
JS vs C++ expression evaluation
我必须将一些算法从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++编写有一个很好的了解。
相关文章:
- 使用正则表达式评估电子邮件地址时出现性能问题
- Javascript-在一行中评估多个正则表达式
- 在JavaScript中评估复杂的数学表达式
- 我可以在对象上下文中评估表达式吗?
- Webpack:是否可以在编译时评估javascript表达式
- AngularJs针对多个条件评估表达式
- 评估JavaScript中给出布尔表达式的字符串
- 在 NodeJS repl 中逐个表达式地评估 Javascript 文件
- JS与C++表达式评估
- 条件表达式的评估
- JavaScript 评估,用于在某种隔离环境中的表达式
- Birt报告引擎.评估Javascript表达式时出错
- 正在评估AngularJS ng-show指令中的表达式
- 正在评估JavaScript代码中的Elisp表达式
- 正在Chrome中评估xpath表达式
- 如何评估JavaScript表达式
- 在winrt/xaml/c#应用程序中动态评估javascript表达式
- AngularJS在评估正则表达式ng模式时出现问题
- 如何在对象上保持表达式's参数,以便重新评估
- 为什么悬停在Chrome调试器实际上修改变量,而不是评估表达式