I am working on a javascript code which calculates the value of Pi. So here's the problem. When eval()
calculates the string which is generated by the code it returns 1 . It is supposed to return 1.49138888889 (which is a rough value of Pi^2/6
).
Here's the code. It returns the correct calculation as a string, But eval()
doesn't calculate it properly.
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.