What's wrong with long? Why is subtracting 1 automatically?

大城市里の小女人 提交于 2021-02-17 06:57:10

问题


#include <iostream>
#include <math.h>
#include <algorithm>

using namespace std;

int main() {
    int t, c1, c2, res;
    string str1, str2;

    cin >> t;

    for (int i = 0; i < t; i++) {
        c1 = c2 = res = 0;
        cin >> str1 >> str2;
        c1 = count(str1.begin(), str1.end(), '1');
        c2 = count(str2.begin(), str2.end(), '1');
        cout << (long)(((pow(10, c1) - 1) / 9) * ((pow(10, c2) - 1) / 9)) << '\n';
    }
}

For input:

1
11111 11111

Output is:

123454321

but, here is the problem,

For input:

1
10101 10100

Output is:

1220

Also, for

1
11000 11000

Output:

120

I'm not getting why long is subtracting 1 from the final answer if the length of answer is less than 4?

Note: Here, input string is of length <= 10^5


回答1:


Some pow implementations return inaccurate results even when exact results are representable. Microsoft’s pow implementation is notorious for this.

In (long)(((pow(10, c1) - 1) / 9) * ((pow(10, c2) - 1) / 9)), pow is returning a value slightly less than the correct value, such as returning 99999.999999999985448084771633148193359375 instead of 100000. This results in the rest of the arithmetic producing a value slightly less than 1221 instead of 1221. When that is converted to long, the fraction is truncated, producing 1220.

Ideally, enough people would complain to Microsoft about this, or other publishers of bad pow routines, that they would fix it.

Given that the problem exists, you can work around it by rounding the pow result to the nearest integer (as with the round function) or by writing your own power routine to suit your purposes.



来源:https://stackoverflow.com/questions/51869997/whats-wrong-with-long-why-is-subtracting-1-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!