Sign in to follow this  

C++, Don't quite get the result I expect...

This topic is 4381 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello there! Thought this would be the place for my small problem. When I convert from decimal to binary bases with a recursive function, it produces only the two last to digits of the result. If I input 54, it produces 00. If I input 55, it produces 01. Here is the code, would be happy if you could helo me. void toBinary(int dec) { int ans; if(dec <= 1){ cout << dec; return; } ans = dec % 2; toBinary(ans >> 1); cout << ans; }

Share this post


Link to post
Share on other sites
toBinary(ans >> 1);
Should be:
toBinary(dec >> 1);
I assume it was a typo and you understand the problem, if you don't please ask why you should do that.

Share this post


Link to post
Share on other sites
Your maths is flawed [smile]
Note that x MOD y returns the remainder of the division of x by y, so your code basically just has four outcomes:
0, 1, 00 and 01 [smile]
[edit]
Ah - beaten to it [smile]
[/edit]

Share this post


Link to post
Share on other sites
Just a guess but I think it's here:

ans = dec % 2;
toBinary(ans >> 1);
cout << ans;

ans can only be 0 or 1 so when it's passed to toBinary "dec<=1" becomes true and it exits.

I think "toBinary(ans >> 1);" should be "toBinary(dec >> 1);".

Edit: aw crap you guys are too fast

Share this post


Link to post
Share on other sites
There's one other thing I am wondering about.. Can I append to an int?

Let me explain what I mean; I have a loop, spitting out numbers like 45, 67, 115, every run. I want a variable that when the loop is over, looks like this: 4567117

Understan me? :)

Share this post


Link to post
Share on other sites
Quote:
Original post by BeatOne
There's one other thing I am wondering about.. Can I append to an int?

Let me explain what I mean; I have a loop, spitting out numbers like 45, 67, 115, every run. I want a variable that when the loop is over, looks like this: 4567117

Understan me? :)


I assume you meant 4567115. If you wanted to store the result as an int you could just for each loop multiply the int with 10[sup]x[/sup]. So if we start with having 45 we assign the "Final" int to 45, we then see 67 is the next number, 67 have two digits so we multiply with 100(two zeros), and then add 67 and then we multiply with 1000 (since 115 have 3 digits) and add 115. So the final calculation would be like this:

Final = (45 * 100 + 67)*1000 + 115

EDIT: A simple (and ugly) code example:

void Add(unsigned int x)
{
static unsigned int Final = 0;

if( 0 == Final )
{
Final = x;
return;
}
// Calculate number of digits of X by taking the log10, adding one and casting to unsigned int.
unsigned int NumDigits = static_cast<unsigned int>(std::log10(static_cast<float>(x))) + 1;
// Get the multiplier by: 10^NumDigits
unsigned int Multiplier = static_cast<unsigned int>(std::pow(10.0F,static_cast<int>(NumDigits) ) );
Final *= Multiplier;
Final += x;

std::cout << "Final: " << Final << std::endl;
}



Share this post


Link to post
Share on other sites
Or, you can use the Standard C++ Library to make life a lot easier [wink]


#include <sstream>
using std::stringstream;
...
int var1 = 45;
int var2 = 67;
int var3 = 115;
...
// Create the stream
stringstream ss;
// Output all the variables here
ss << var1;
ss << var2;
ss << var3;
// ss.str(), which returns a string, is now "4567115", but it's a string and you want an int
// Store the int
int result = 0;
// extract the result
ss >> result;
// Now, result == 4567115, and you have your combined int, if you just wanted that string, use the ss.str() function.

Share this post


Link to post
Share on other sites
I used the method you guys said, I got it to work exept one small detail. It only saves the first number, aka the first loop-round..

stringstream ascii;

while(tWord[x] != '\0')
{
ans = int(tWord[x]);
toBinary(ans);
ascii << ans;
x++;
}
int result = ans;
cout << endl << endl << ans;


The whole application takes a string, converts to its ascii equevilants, converts the ascii number to binary. I want to write out not only the binary, but the ascii numbers..

"The word: BeatOne is
10010-blabla in binary
and 11547-blabla-some-more in asciicode."

Share this post


Link to post
Share on other sites
Quote:
Original post by BeatOne
When I convert from decimal to binary bases [...]

void toBinary(int dec)

You don't (and thus the name of your parameter is misleading). All you do is print the binary representation of a number. The number itself is NOT decimal. For example you could write:

toBinary(0x10);
toBinary(020);

And get the result 10000 onscreen. No need to write seperate toBinary methods for decimal, hexadecimal and octal. BTW the internal representation of numbers in a computer is already binary. Funny, huh? :)

Share this post


Link to post
Share on other sites
There is no such thing as converting an integer variable (int, short, long, etc.) from base X to base Y. It is a variable which represents some value, and does so by having some pattern of bits. If I have fifty-four pennies, then I may write that as 54 pennies in decimal or 0x36 pennies in hex or 066 pennies in octal or 110110 pennies in binary, but I still have the same amount of money.

Instead, there are such things as:

a) outputting a text representation of a number in base Y.
b) inputting a number from what is assumed to be a text representation in base X.

Also, don't use char arrays to represent your text. Use std::string.

Share this post


Link to post
Share on other sites
For the case of writing out the binary representation of an integer...

std::bitset<sizeof(int) * 8> bs(val);
std::cout<<bs;

Boy isn't the standard library nice?

Share this post


Link to post
Share on other sites

This topic is 4381 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this