2015-11-13 41 views
2

我已經顯示了兩段代碼。我不太明白如何使用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? 
+5

'pow()'操作(並返回)一個浮點數。浮點數本質上是不精確的。 –

+0

謝謝,但是我們如何知道哪種用法可以正常工作? – Sreenidhi

+5

定義「正確」。浮點數在本質上是不精確的。您只能詢問coputation錯誤是否在可接受的範圍內。查看[每個計算機科學家應該瞭解的有關浮點運算的知識](http://floating-point-gui.de/)以獲取詳細信息。 – Angew

回答

2

很顯然的是,值給你的麻煩是n=1000000000,或10 。 2的最大積分功率小於或等於此值爲2 。您試圖計算的總和爲(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); 
相關問題