我展示了两段代码。我不太明白如何以不同的方式使用 pow() 会导致这些代码中的差异。预先非常感谢。
在这个问题中,你要计算从 1 到 n 的所有整数的总和,但你应该取总和中带负号的 2 的所有幂。例如,对于 n = 4,总和等于 - 1 - 2 + 3 - 4 = - 4,因为1、2和4分别是20、21和22。计算 n 的 t 值的答案。
#include<bits/stdc++.h>
typedef long long ll;
typedef double dl;
using namespace std;
int main() {
ll n,t;
ll i,cnt=0;
cin>>t;
while(t--)// for 't' number of test cases
{
cin>>n;
for(i=1,cnt=0;i<=n;i*=2,cnt++); //counting number of terms in the GP:1,2,4,....
cout<<setprecision(20)<<((n*(n+1))/2)-(2*(pow(2,cnt)-1))<<endl;
}
return 0;
}
//output for above code:499999998352516352
// and the slightly modified code..
#include<bits/stdc++.h>
typedef long long ll;
typedef double dl;
using namespace std;
int main() {
ll n,t;
ll i,cnt=0;
cin>>t;
while(t--)// for 't' number of test cases
{
cin>>n;
for(i=1,cnt=0;i<=n;i*=2,cnt++);
ll k=(pow(2,cnt)); //instead of directly printing the answer, 'k' is computed and then used to find the answer.
cout<<setprecision(20)<<((n*(n+1))/2)-(2*(k-1))<<endl;
}
return 0;
}
//output for above code:499999998352516354
// the second one is the correct answer, the first one is wrong. how does pow() change the values here?
最佳答案
显然,给您带来麻烦的值为 n=1000000000
,即 109。小于或等于该值的最大2的积分幂为229。因此,您尝试计算的总和为 (10^9*(10^9+1))/2-2*(2^30-1),或 500000000500000000-2147483646,或 499999998352516354。
您的第二种方法之所以有效,是因为二次方是精确的,并且您在减法中使用了整数算术。您的第一种方法失败了,因为表达式被计算为 double 。第一项 n*(n+1)/2
或 500000000500000000 是“精确的”,这意味着浮点表示没有错误。第二项 2147483646 也是精确的。在这种情况下,问题出现在减法中。两者之间的差异是不精确的,这意味着您失去了精度。
您没有理由使用pow
。您已经计算了 pow(2,cnt)
。事实上,您根本不需要 cnt
。只需使用
ll k;
for(k=1; k<=n; k*=2);
关于c++ - 在不同地方使用时,在 C++ 中使用 pow() 会有不同的答案,尽管预期相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33698739/