-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
[js] 第100天 分别封装精确运算的加减乘除四个方法 #981
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
只会整数运算,不会小数。 前几天刚练习用 C++ 写这东西,头疼就不再用 js 写一遍了。 基本上就是数组中每个成员存储一位,[0] 是个位,[1] 是十位,以此类推,然后计算时模拟竖式计算处理进位、借位。 除法太难不会,至少加减乘都还比较好写。
|
刚好最近有写过,用来处理小数计算时的精度问题。
|
@foreverZ133 你的写法可以处理小数的不精确问题,但是无法处理大整数导致的 这里贴上一段最近写的处理大整数加法的 C++ 代码,抛砖引玉。 struct bigint {
static const int limit = 10;
int num[100003] { 0 };
size_t size = 0;
bigint() { bigint(0); }
explicit bigint(unsigned long long i) {
int pos = 0;
while (i) {
num[pos] = i % limit;
pos++;
size++;
i /= 10;
}
}
explicit bigint(const string &s) {
size = s.size();
for (int i = 0; i < s.size(); i++) {
num[i] = s[size - i - 1];
}
}
int &operator [](size_t rhs) {
bigint &lhs = *this;
return lhs.num[rhs];
}
int operator [](size_t rhs) const {
const bigint &lhs = *this;
return lhs.num[rhs];
}
bigint operator +(const bigint &rhs) const {
const bigint &lhs = *this;
size_t mlen = max(lhs.size, rhs.size);
bigint result;
for (size_t i = 0; i < mlen || result[i] >= limit; i++) {
if (i < mlen)
result[i] += lhs[i] + rhs[i];
result.size = i + 1;
if (lhs[i] + rhs[i] >= limit) {
result.size++;
result[i + 1] += result[i] / 10;
result[i] = result[i] % 10;
}
}
return result;
}
}; |
function Calculate() {
// 获取小数位数
const getMaxDigit = (x, y) => {
const xStr = String(x)
const yStr = String(y)
const xIndex = xStr.indexOf('.')
const yIndex = yStr.indexOf('.')
return Math.max((xStr.length - xIndex + 1), (yStr.length - yIndex + 1))
}
const add = (x, y) => {
let digit = getMaxDigit(x , y)
let exponent = 1
while (digit--) {
exponent *= 10
}
return (x * exponent + y * exponent) / exponent
}
const subtract = () => {
}
const multiply = () => {
}
const divide = () => {
}
return {
add,
subtract,
multiply,
divide
}
}
const { add } = new Calculate()
add(0.1, 0.2) |
|
第100天 分别封装精确运算的加减乘除四个方法
The text was updated successfully, but these errors were encountered: