我已經顯示了兩段代碼。我不太明白如何使用pow()不同地帶來這些代碼的差異。提前致謝。不同的答案在C++中使用pow()時,在不同的地方使用powe(),但預期相同
在這個問題中,你要計算從1到n的所有整數的總和,但是你應該在總和中取負所有的兩個冪。例如,對於n = 4,總和等於-1 - 2 + 3 - 4 = - 4,因爲1,2和4分別是2 ,2 和2 。計算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?
'pow()'操作(並返回)一個浮點數。浮點數本質上是不精確的。 –
謝謝,但是我們如何知道哪種用法可以正常工作? – Sreenidhi
定義「正確」。浮點數在本質上是不精確的。您只能詢問coputation錯誤是否在可接受的範圍內。查看[每個計算機科學家應該瞭解的有關浮點運算的知識](http://floating-point-gui.de/)以獲取詳細信息。 – Angew