我正在用duktape和C语言测试实时算法的采用,但是发现返回的结果并不总是正确的。一个简单的示例,将三个浮点数传递给javascript引擎并进行一些简单的指数计算,结果令人惊讶地返回了整数值!
/*
* Very simple example program
*/
#include "duktape.h"
#define MAX_FILE_BUFF 65536
void doTest(duk_context *ctx, double x, double y, double z) {
if (duk_get_global_string(ctx, "GetAlgorithmResult")) {
duk_push_number(ctx, x);
duk_push_number(ctx, y);
duk_push_number(ctx, z);
duk_call(ctx, 3);
printf("ALGO(%f,%f,%f) => result = %.6lf\n", x, y, z, duk_get_number(ctx, -1));
duk_pop(ctx);
} else {
printf("did not see the func in duk!\n");
}
}
int main(int argc, char *argv[]) {
duk_context *ctx = duk_create_heap_default();
char js_code_string[MAX_FILE_BUFF];
FILE *jsfp = fopen("algorithm.js", "r");
(void) argc; (void) argv; /* suppress warning */
if (jsfp != NULL) {
fread(js_code_string, 1, MAX_FILE_BUFF, jsfp);
fclose(jsfp);
duk_eval_string(ctx, js_code_string);
duk_pop(ctx); /* pop eval result */
doTest(ctx, 1.0011, 2.3344, 3.4321);
doTest(ctx, 3.0011, 4.3344, 7.4321);
doTest(ctx, 5.0011, 2.3344, 9.4321);
doTest(ctx, 7.0011, 8.3344, 2.4321);
} else {
printf("cannot find the js code to load!!\n");
}
duk_destroy_heap(ctx);
return 0;
}
使用如下的algorithm.js:
function GetAlgorithmResult(x, y, z) {
// this is a testing algorithm calculation in javascript code
var r = (x ^ y + z);
return r;
}
给出的结果:
ALGO(1.001100,2.334400,3.432100) => result = 4.000000
ALGO(3.001100,4.334400,7.432100) => result = 8.000000
ALGO(5.001100,2.334400,9.432100) => result = 14.000000
ALGO(7.001100,8.334400,2.432100) => result = 13.000000
如果算法更改为:
function GetAlgorithmResult(x, y, z) {
// this is a testing algorithm calculation in javascript code
var r = x * y * z;
return r;
}
结果正确:
ALGO(1.001100,2.334400,3.432100) => result = 8.020707
ALGO(3.001100,4.334400,7.432100) => result = 96.676518
ALGO(5.001100,2.334400,9.432100) => result = 110.115691
ALGO(7.001100,8.334400,2.432100) => result = 141.912957
请有人帮忙!
答案 0 :(得分:0)
^
是javascript中的按位运算符,而不是指数,看起来像您想要的那样。使用Math.pow(x,y)
代替x ^ y
。