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;
}