JS vs C++表达式求值 我必须把一些算法从JavaScript改写为C++。所以我有一个问题:我应该注意什么?JS与C+++之间的评价有什么不同?

JS vs C++表达式求值 我必须把一些算法从JavaScript改写为C++。所以我有一个问题:我应该注意什么?JS与C+++之间的评价有什么不同?,javascript,c++,expression,Javascript,C++,Expression,例如,此算法: 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 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;
当我简单地将变量改为双变量和数学时。对于std::,它将编译,但表达式中的-=将导致UB我的编译器显示它


<你知道什么其他的棘手的区别吗?< /P> < P> JavaScript和C++是非常不可比的。就像苹果和桔子。这两种语言都可以执行计算/功能,就像苹果和橙子都是水果一样,但它们几乎没有相似之处

这是一个C++实现的JavaScript代码:

#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++中写下代码。

你可能想阅读关于序列点、顺序和排序的问题。这个问题是巨大的,不太可能完全回答。除非你希望我们在这里重印一些教科书。@Deduplicator我不认为这个例子中的评估顺序有太多不同。未定义的行为可以通过从整数中减去float或类似的方式引起。它也很大程度上取决于编译的编译器和编译代码的OS。@ Visual:你也应该阅读C++的主题。从整数中减去浮点并不是问题。@ DeDePrimor请在当前示例中按计算顺序不同的方式计算。我不是C++初学者。C++的表达式语法与JS非常相似,但语义却完全不同。许多JS算术表达式是有效的可编译C++表达式。我想问的是这些语言中表达语义的差异,而不是整个语言的比较。在两种语言中都有效但会产生不同结果的表达式。