Ask your own question, for FREE!
Computer Science 16 Online
OpenStudy (christos):

Can you help me with C++? This program is supposed to read a number (only from 0 to 31) and display it in binary. How ever when I run it it crashes. I dont know the reason. Can you help me please?

OpenStudy (christos):

// // main.cpp // week4-5 // #include <iostream> using namespace std; int main() { int number,a,b,c,d,e,f; cin >> number; a = number%2; number = number/2; b = number%2; number = number/2; c = number%2; number = number/2; d = number%2; number = number%2; e = number%2; number = number/2; f = number%2; cout << f << e << d << c << b << a; return 0; }

OpenStudy (espex):

It worked for me, are you getting any error when it crashes?

OpenStudy (espex):

It completed, let me say that, since I input a 10 and it spat out 011010

OpenStudy (christos):

for real now? It worked for you?

OpenStudy (espex):

result: Success time: 0s memory: 2900 kB returned value: 0 input: 10 output: 011010

OpenStudy (christos):

but thats not the correct binary number for 10 isnt it ;/ ?

OpenStudy (espex):

It is not. The correct binary should be 1010

OpenStudy (espex):

result: Success time: 0s memory: 2900 kB returned value: 0 input: 6 output: 000110

OpenStudy (espex):

6 is correct though.

OpenStudy (christos):

yea, pretty weird

OpenStudy (espex):

It just means that you are doing a check more times than necessary with a multi-digit number. Something that could be fixed pretty easily.

OpenStudy (christos):

Can you help me?

OpenStudy (espex):

I can try, but we would need to figure out why it crashes for you first.

OpenStudy (christos):

Yea I fixed the crash. Now all that is left is that illogical outcome

OpenStudy (espex):

You need to do a check for value = 1. Looks like it mods down until the number is less than 1 and adds an extra '1'

OpenStudy (christos):

hmm let me see

OpenStudy (christos):

I can't the line on which I am incorrect :/

OpenStudy (espex):

You need to put it into a loop with a condition to check for 1, or you need to place an if statement after each division to break out once you have a "number" equal to 1.

OpenStudy (christos):

I found it, it was really a small detail. :)

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!