问题描述
#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';
}
}
输入:
1
11111 11111
输出为:
123454321
但是,这是问题所在,
输入:
1
10101 10100
输出为:
1220
还
1
11000 11000
输出:
120
我不明白为什么如果答案的长度小于4,那么从最终答案中减去1会是多长?
I'm not getting why long is subtracting 1 from the final answer if the length of answer is less than 4?
注意:此处,输入字符串的长度为< = 10 ^ 5
推荐答案
某些 pow
实现会返回不准确的结果,即使精确的结果是可表示的.微软的 pow
实现为此而臭名昭著.
Some pow
implementations return inaccurate results even when exact results are representable. Microsoft’s pow
implementation is notorious for this.
在(long)(((pow(10,c1)-1)/9)*((pow(10,c2)-1)/9))
, pow
返回的值略小于正确的值,例如返回99999.999999999985448084771633148193359375而不是100000.这导致该算术的其余部分生成的值略小于1221而不是1221.将其转换为long
,则分数被截断,生成 1220
.
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
.
理想情况下,足够多的人会向Microsoft或其他错误的 pow
例行程序发布者抱怨,他们会解决此问题.
Ideally, enough people would complain to Microsoft about this, or other publishers of bad pow
routines, that they would fix it.
鉴于问题存在,您可以通过将 pow
结果四舍五入到最接近的整数(与 round
函数一样)或通过编写自己的幂来解决符合您目的的常规程序.
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.
这篇关于长期怎么了?为什么要自动减去1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!