1

I have been learning C++ for about a month. And I made a binary converter. But when I input a large number,such as 200000000,it will return a wrong answer. So I changed all int into double and changed some codes,but it was still wrong.Then I searched for the solution on Google,but I got nothing. Please point out my mistake!Thanks! Below is the code.

(Sorry for my poor English and it's my first time asking a question on this website.If I made anything wrong,please point it out and forgive me.)

#include <iostream>
#include <cmath>
using namespace std;
int main(){
    double m,n,t,x,i=0;
    cin>>n;
    m=n;
    do{
        if(fmod(n,2)==0) n/=2;
        else n=(n-1)/2;
        i++;
    }while(n>=1);
    for(t=0;t<i;t++){
        x+=fmod(m,2)*pow(10,t);
        if(fmod(m,2)==0) m/=2;
        else m=(m-1)/2;
    }
    printf("%.f\n",x);
    return 0;
}
Pratik Deoghare
  • 35,497
  • 30
  • 100
  • 146
creeper
  • 13
  • 2
  • 4
    `double` is the wrong variable type for this. You Need to use `long` or `long long` – Thomas Sparber Oct 30 '15 at 15:24
  • First rule of floating-point - nobody talk.. no, nobody uses floating point unless they have to. – Martin James Oct 30 '15 at 15:35
  • What is your maximum number that you need to convert? –  Oct 30 '15 at 15:58
  • 1
    Every primitive data type has a maximum value. Using a bigger type is just a workaround. I recommend you research ways of detecting input strings that represent values which are too high. Try to write a program which behaves nicely (e.g. printing an error message) if I enter "100000000000000000000000000000". – Christian Hackl Oct 30 '15 at 16:01

1 Answers1

3

You should change double to unsigned long long but it won't help because of the following code.

        x+=fmod(m,2)*pow(10,t);
        if(fmod(m,2)==0) m/=2;
        else m=(m-1)/2;

This code converts m to decimal so that it can be printed. But since it shifts ones by powers of 10 it goes beyond the range of even unsigned long long.

It can be fixed by declaring x as a string. Change fmod to %.

And

    x+=fmod(m,2)*pow(10,t);

to

x = ((m%2)? "1":"0") + x ;

and cout << x << endl; at the end. Good luck!

Pratik Deoghare
  • 35,497
  • 30
  • 100
  • 146