Question
The following code is in C++ language. 1) I need help with my Base10toBase2 function. It should only be able to take in positive integers
The following code is in C++ language.
1) I need help with my Base10toBase2 function. It should only be able to take in positive integers from the user. If a negative integer (such as -1) or a decimal (such as 2.3) is entered, it should re-prompt the user to enter a valid positive integer.
2) What's the reasoning behind having two longs in a row? (Example: long long n, o;) (Example #2: long long BinaryNo = 0;)
Below is my C++ code:
#include #include #include using namespace std;
string bn;
int input(long long); // function to Input of Base 2 value to enforce the entry of only 1's and 0's
int Base10toBase2(long long); // Base 10 to Base 2
int Base2toBase10(long long); //Base 2 to Base 10
int main(){ long long n, o; cout << "Enter a decimal number: "; cin >> n; while(1){ cout << "Enter a binary number: "; cin >> o; if(input(o)){ break; } else{ cout << "Entered number is not a binary number. Please try again." << endl; } }
cout << endl; cout << n << " in decimal = " << Base10toBase2(n) << " in binary" << endl; cout << o << " in binary = " << Base2toBase10(o) << " in decimal"; return 0; }
int Base10toBase2(long long n){ long long BinaryNo = 0; int remainder, i = 1; while (n!=0){ remainder = n % 2; n /= 2; BinaryNo += remainder * i; i *= 10; }
return BinaryNo; }
int Base2toBase10(long long o){ int DecimalNo = 0, i = 0, remainder; while (o!=0){ remainder = o % 10; o /= 10; DecimalNo += remainder * pow(2, i); ++i; }
return DecimalNo; }
int input(long long num){ long long x;
while(num){ x = num % 10; if((x == 0) || (x == 1)){ num = num / 10; } else{ return 0; } } return 1; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started