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?
// // 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; }
It worked for me, are you getting any error when it crashes?
It completed, let me say that, since I input a 10 and it spat out 011010
for real now? It worked for you?
result: Success time: 0s memory: 2900 kB returned value: 0 input: 10 output: 011010
but thats not the correct binary number for 10 isnt it ;/ ?
It is not. The correct binary should be 1010
result: Success time: 0s memory: 2900 kB returned value: 0 input: 6 output: 000110
6 is correct though.
yea, pretty weird
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.
Can you help me?
I can try, but we would need to figure out why it crashes for you first.
Yea I fixed the crash. Now all that is left is that illogical outcome
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'
hmm let me see
I can't the line on which I am incorrect :/
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.
I found it, it was really a small detail. :)
Join our real-time social learning platform and learn together with your friends!