Hey guys,

As stated in the title, could somebody help me tidy up my program?

The question for this task was:
Using vectors create a program that converts randomly generated
integer numbers between 0 and 10 to binary and displays the converted numbers.
Sample Output:
Decimal Binary
1 1
2 10
3 11

Currently my code is outputting the random integers and binary numbers... but they're all jumbled up and not spaced apart...the binary numbers are also being displayed backwards (you have to read them from right to left).

Could somebody help me sort these problems out?
Here is my program.

 ``123456789101112131415161718192021222324252627282930313233343536373839404142`` ``````#include #include #include #include using namespace std; int main() { cout<<"Converting decimal to binary"< numbersToBeConverted;// This creates the vector where our randomly generated decimal numbers will be stored for(int i= 0; ibin; for(int j = 0; j < numbersToBeConverted.size(); j++) { cout<0) { binary = (randomNum%2); randomNum /= 2; bin.push_back(binary); } for(int a = 0; a < bin.size(); a++) { cout<< bin[a] <<" "; } } return 0; }``````
 ``123456789101112131415161718192021222324`` ``````#include #include #include #include #include int binary( int n ) { if( n == 0 ) return 0 ; else return binary(n/2) * 10 + n%2; } int main() { std::cout<<"Converting decimal to binary\n\n" ; std::srand( std::time(nullptr) ) ; const std::size_t sz = 1 + std::rand()%5 ; std::vector numbers(sz) ; for( int& v : numbers ) v = rand()%10; for( int n : numbers ) std::cout << n << ' ' << std::setw(4) << std::setfill('0') << binary(n) << '\n' ; }``````

http://coliru.stacked-crooked.com/a/07c14d94946d4315
Last edited on
 ``123456789101112131415161718192021222324252627282930313233`` ``````#include #include #include #include #include int main() { std::cout<<"Converting decimal to binary\n\n" ; std::srand( std::time(nullptr) ) ; const std::size_t n = 1 + std::rand()%5 ; for( std::size_t i = 0 ; i < n ; ++i ) { int number = std::rand()%10 ; std::cout << number << ' ' ; std::vector binary ; while( number > 0 ) { binary.push_back( number%2 ) ; number /= 2 ; } binary.resize(4) ; std::reverse( binary.begin(), binary.end() ) ; for( int b : binary ) std::cout << b ; std::cout << '\n' ; } }``````

http://coliru.stacked-crooked.com/a/c4c1eec9bce5877d
Last edited on
Topic archived. No new replies allowed.