简体   繁体   English

我无法使用 eval() 来处理我的 javascript 计算

[英]I can't get eval() to work with my javascript calculation

I am working on a javascript code which calculates the value of Pi.我正在编写用于计算 Pi 值的 javascript 代码。 So here's the problem.所以问题来了。 When eval() calculates the string which is generated by the code it returns 1 .eval()计算由代码生成的字符串时,它返回 1 It is supposed to return 1.49138888889 (which is a rough value of Pi^2/6 ).它应该返回 1.49138888889 (这是Pi^2/6的粗略值)。

Here's the code.这是代码。 It returns the correct calculation as a string, But eval() doesn't calculate it properly.它以字符串形式返回正确的计算,但eval()没有正确计算它。

function calculate() {
  var times = 10;
  var functionpart1 = "1/";
  var functionpart2 = "^2+";
  var x;
  for (var functionpistring = "", x = 1; times != 0; times--, x++) {
    functionpistring = functionpistring + functionpart1 + x.toString() + functionpart2;
  }
  document.getElementById("value").innerHTML = eval(functionpistring.slice(0, functionpistring.length - 1));
}
function calculate() {
    var times = 20, // max loops
        x,          // counter
        f = 0,      // value representation
        s = '';     // string representation
    function square(x) {
        return x * x;
    }
    function inv(x) {
        return 1 / x;
    }
    function squareS(x) {
        return x + '²';
    }
    function invS(x) {
        return '1 / ' + x;
    }
    for (x = 0; x < times; x++) {
        f += square(inv(x));
        s += (s.length ? ' + ' : '') + squareS(invS(x));
        document.write(f + ' = ' + s);
    }
}
calculate();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM