2016-06-09 73 views
3

我的代碼正在爲輸入100打印192(這是所需的結果)。但是當我把它提交給在線裁判時,它顯示我的程序輸出100的輸出是190.我複製並粘貼了ideone.com中的代碼並輸入了100我得到了結果192.我將它發送給我的朋友而在他的電腦上,輸出是190.但他也將代碼提交到ideone.com並得到了192個。問題是什麼?這裏是我的代碼:C++程序在不同的計算機上給出不同的結果

#include <bits/stdc++.h> 
using namespace std; 

typedef long long int lli; 

int main(){ 
    lli in,ans = 0; 
    cin >> in; 

    if(in < 10) 
     cout << in << endl; 
    else{ 
     lli digits = 0; 
     lli temp = in; 
     while(temp > 0){ 
     digits++; 
     temp /= 10; 
     } 
    digits--; 

    while(in > 0){ 
     //cout << "in: " << in << endl; 
     //cout << "digits: " << digits << endl; 

     ans += ((in - (pow(10,digits) - 1)) * (digits + 1)); 
     in = in - (in - (pow(10,digits) - 1)); 
     digits--; 

     if(in == 9){ 
      ans+= 9; 
      break; 
     } 
     } 
     cout << ans << endl; 
    } 
} 

ideone鏈接:http://ideone.com/zOvHzW

這究竟是爲什麼?我明白這可能是一個編譯器問題,但是這裏真正發生了什麼?

+0

閱讀CodeChef有關如何處理輸入和輸出的指南! :) – Ajay

+0

注意,[不要'#include '](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h ) – CoryKramer

+0

爲什麼不包含? –

回答

1

問題是std::pow不準確。這是一個近似算法。它返回的浮點結果可能會有一些非常小的數值。

當您將浮點數轉換爲整數時,通過刪除小數部分將其舍入。但是,如果正確的結果會一直說100,誤差爲-0.000...001,因此結果是99.999...999,你切斷小數部分,那麼你得到的整數爲99

std::pow實現如何。 ..具體到實施者。因此,錯誤可能是一種編譯器/計算機的一種方式,但另一種方式可能是另一種方式。這就是結果可能不同的原因。

解決方案:請勿使用std::pow進行整數計算。

解決方法:將結果取整爲最接近的整數。

+0

它的工作。謝謝! –

+0

@RedwanulSourav無需感謝,這就是upvote按鈕的用途。並且不要忘記將最有幫助的答案標記爲已接受:) – user2079303

相關問題