Reputation: 141
# include <iostream>
# include <cmath>
using namespace std;
int main()
{
int p;
int n;
int q;
cin>>n;
int r;
r=0;
for (int i=0,n; n>1; i=i+1,n=n/2)
{
p=n%2;
q= p*(pow(10,i));
r=r + q;
}
cout<<r;
system("pause");
return 0;
}
I am not supposed to use arrays. It compiles fine but when executed and a number is entered, it doesn't produce the desired results. For instance, when 22 is entered, it gives -2147483648 whereas the desired output would be 10110.
Upvotes: 0
Views: 76
Reputation: 2351
your way is limited and not effient in converting to binary
you should use string it's more helpful and the range is big enough for any number
this is my code for decimal-to-binary
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main()
{
long long n;
string s,bin;
stack<string> res;
cin>>n;
while(n>0)
{
if(n%2==0)
s='0';
else
s='1';
res.push(s);
n=n/2;
}
while(!res.empty())
{
bin=bin+res.top();
res.pop();
}
cout<<bin<<endl;
return 0;
}
I hope it will help you.
Upvotes: 1
Reputation: 88027
int i=0,n;
should be
int i=0;
I don't know what you thought you were doing there, but what you are actually doing is declaring another variable n
. Because the second n
variable doesn't have a value the rest of the code doesn't work.
That's not the only problem with your code, but I'm sure you can figure out the rest.
Upvotes: 0