0

This is with regards to Codeforces question - 1352A Sum of Round Numbers. When I compiled the following code on the website using compiler GNU G++17 7.3.0 I successfully got the desired result, for example, with the test case 9878 my code gave the correct output viz. 6 70 800 9000 however when I compiled the same code using GNU G++11 5.1.0 I got an output 6 70 799 9000 . Can someone please explain the reason behind 799?

#include <bits/stdc++.h>
using namespace std;
int main(){
    int n, num, len, count=0;
    // string num_str;
    cin>>n;
    for(int i=0; i<n; i++){
        count=0;
        vector<int> vec;
        cin>>num;
        len =  to_string(num).length();
        for(int i=len-1; i>-1; i--){
            if(num%10 == 0){
                num = num/10;
            }
            else{
                // count++;
                vec.push_back((num%10)*pow(10,count));
                num /=10;
            }
            count++;
        }

        cout<<"\n"<<vec.size()<<"\n";
        for(auto j=vec.begin(); j!=vec.end(); ++j){
            cout<<" "<<*j<<" ";
        }
    
    }
    
}

Here's the link referencing my code - link. Thanks!

  • 2
    `pow(10,count)` is designed to handle just about anything and will drop into floating point arithmetic when it needs to. [Floating point math is imprecise](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) and sometimes you wind up not with 800, but with 799.9999999999, which truncates to 799 when converted back into an integer. Don't use `pow` for this job. Refactor your code to multiply instead. Your version of GCC likely has some extra smarts lacking in 5.1 that realizes it can compute entirely in integer space and avoids the problem. – user4581301 Jul 09 '20 at 18:53
  • 1
    Extra unrelated reading: [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) and [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h). Combine the two and the resulting bugs can get inscrutable. – user4581301 Jul 09 '20 at 19:09
  • Thanks, makes sense. On a side note, found this snippet as well, it reiterates the same fact. https://codeforces.com/blog/entry/21844 – Tantalize zing Jul 09 '20 at 19:22
  • In your specific case, instead of `pow` and `count++`, consider `count *= 10;`. You have to keep an eye out for integer overflow, but you need to be wary of it with `pow` anyway. – user4581301 Jul 09 '20 at 19:24
  • @user4581301 Please use the answer section for your answers – Asteroids With Wings Jul 09 '20 at 19:24
  • I have a better idea. It just took a while to find a good one. – user4581301 Jul 09 '20 at 19:25

0 Answers0