#include <iostream>
#include <string>
using namespace std;
string reverse (string s)
{
string result(s);
int i = 0;
for (int i = 0, j = s.length() - 1; i <s.length(); i++, j--)
result[i] = s[j];
return result;
}
string convertDecimalToBinary(int value)
{
string s;
int x = 1;
int y = 0;
while (value != 0)
{
int number = value % 2;
if (number == 1)
s.append(1, x);
if (number == 0)
s.append(1, y);
value = value / 2;
}
return reverse(s);
}
int main()
{
cout << "Enter a decimal number: ";
int number;
cin >> number;
cout << convertDecimalToBinary(number) << endl;
return 0;
}
Cannot figure out why it is printing incorrectly
Page 1 of 14 Replies - 155 Views - Last Post: 05 February 2012 - 12:10 PM
Topic Sponsor:
#1
Cannot figure out why it is printing incorrectly
Posted 05 February 2012 - 11:46 AM
I am having trouble with this code. I am trying to convert decimal to binary using string functions and when it runs I get weird symbols instead of the binary digits. Help please?
Replies To: Cannot figure out why it is printing incorrectly
#2
Re: Cannot figure out why it is printing incorrectly
Posted 05 February 2012 - 11:56 AM
Just looking at this quickly it may be because you're appending the integer values 0 or 1, which in ASCII corresponds to something else. What you want is the ASCII representation of 0 or 1, which would be 48 and 49. This can be fixed by maybe this
Hope I've helped
if (number == 1) s.append(1, '1'); if (number == 0) s.append(1, '0');
Hope I've helped
#3
Re: Cannot figure out why it is printing incorrectly
Posted 05 February 2012 - 11:59 AM
s.append(1, x);
that dosn't do what you think it does; that appends the assci character with value '0' which is a control character not the decimal '0'; instead just use s.push_back('0') and s.push_back('1')
#4
Re: Cannot figure out why it is printing incorrectly
Posted 05 February 2012 - 12:09 PM
#5
Re: Cannot figure out why it is printing incorrectly
Posted 05 February 2012 - 12:10 PM
I took your C++ and made minor syntactical changes to make it C# so I could follow it and produce some breakpoint results.
I fed the function the number 47
The first function produced 111101
The second produced 101111


So to me its seems you logic is sound. So it has to be some of your statements don't work the way you assume they do. I'm going to guess the string.append might be worth a read.
Update... Looks like some others type faster than I do.
I fed the function the number 47
The first function produced 111101
The second produced 101111


So to me its seems you logic is sound. So it has to be some of your statements don't work the way you assume they do. I'm going to guess the string.append might be worth a read.
Update... Looks like some others type faster than I do.
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote








|