JavaScript Pi Spigot算法不工作
JavaScript Pi Spigot Algorithm not working
我已经翻译了以下C++代码:
#include <iostream>
using namespace std;
#define NDIGITS 100
#define LEN (NDIGITS/4+1)*14
long a[LEN];
long b;
long c = LEN;
long d;
long e = 0;
long f = 10000;
long g;
long h = 0;
int main(void) {
cout<<b<<endl;
for(; (b=c-=14) > 0 ;){
for(; --b > 0 ;){
d *= b;
if( h == 0 )
d += 2000*f;
else
d += a[b]*f;
g=b+b-1;
a[b] = d % g;
d /= g;
}
h = printf("%ld",e+d/f);
d = e = d % f;
}
getchar();
return 0;
}
进入JavaScript:
function mod(n, m) {
return ((m % n) + n) % n;
} // mod function to fix javascript modulo bug
function calculate(NDIGITS){
var LEN = (NDIGITS / 4 + 1) * 14,
out = "",
a = [],
b = 0,
c = LEN,
d = 0,
e = 0,
f = 10000,
g = 0,
h = 0;
for( ; a.length != LEN; a.push(0));
for( ; (b=c-=14) > 0 ; ){
for(; --b > 0 ;){
d *= b;
if(h == 0)
d += 2000*f;
else
d += a[b]*f;
g=b+b-1;
a[b] = mod(d, g);
d /= g;
};
h = 4;
out += e + d / f;
d = e = mod(d, f);
};
return out;
};
calculate(100);
问题是,C++(这是正确的)输出看起来像这样:
314159265358979323846264338327952884197169399375105820974944592307816406286208998628034825342117067
但是JavaScript(这是错误的)输出看起来是这样的:
3141.59265358979345928.3358757688158002.0385670499462603.1996016540431161.44919092773639662.2465149363658988.6127837844255865.38922090756173.61883094848226189.6324225085448150.3443440509899223.2179589088062808.1943642437717982.8973948575671840.86646781354151140.38694447211833938.5632867441137341.458720505086448.7384444661472807.14448220310268936.5521832735086764.9290682040381301.76585926509928223.4135991546457438.115065010927
我的编码哪里搞砸了感谢您的帮助。
- JavaScript做浮点除法
- 模计算函数中交换的参数
以下代码产生的结果与为给定样本(100)数字提供的C++代码相同:
function mod(m, n) {
return ((m % n) + n) % n;
} // mod function to fix javascript modulo bug
function calculate(NDIGITS) {
var LEN = (NDIGITS / 4 + 1) * 14,
out = "",
a = [],
b = 0,
c = LEN,
d = 0,
e = 0,
f = 10000,
g = 0,
h = 0;
for (; a.length !== LEN; a.push(0));
for (; (b = c -= 14) > 0;) {
for (; --b > 0;) {
d *= b;
if (h === 0) {
d += 2000 * f;
} else {
d += a[b] * f;
}
g = b + b - 1;
a[b] = mod(d, g);
d = Math.floor(d / g);
}
h = Math.floor(e + d / f);
out += h;
h = h.length;
d = e = mod(d, f);
}
return out;
}
console.log(calculate(100));
相关文章:
- 解释一下这个排序算法是如何工作的?
- 快速排序函数在快速排序算法中如何工作?
- 尝试实现二叉搜索算法,似乎无法使其工作
- 你不能在 void 指针上使用指针算法,那么 void 指针数组是如何工作的呢?
- 带有 SFML 的 c++ 中的过程无法正常工作,移动算法
- 在钟形福音算法的工作中陌生
- 贪婪算法练习无法正常工作
- 我无法获得基于读取字符数组的算法来工作
- 素测试算法无法正常工作
- 这种计算 32 位整数中设置位数的算法如何工作
- 这种珠子排序算法的 c++ 实现是如何工作的
- CYK算法是如何工作的
- 理解算法二叉搜索背后的工作原理C++问题
- C++ 二叉搜索算法像lower_bound一样工作
- 为什么 std::算法也不直接在容器上工作?
- 通过修改二叉搜索算法来改进它,使其在搜索大量单词(单词列表)中的单词时工作得更快
- 通过使用两个凸壳的切线来合并它们的算法在实践中是如何工作的
- JavaScript Pi Spigot算法不工作
- 归并排序算法不能正常工作
- 快速排序算法不能正常工作