This is what the assignment says to do: Write a C++ program to do decimal-binary number conversions. The program gives the user a choice of conversion type (binary to decimal or decimal to binary). After the user makes a selection and enters an original datum to convert, the program should check if the input is valid. The user will be asked to reenter data until the input is acceptable. Finally, the original number and the converted form are both shown on the screen.
The main( ) function should be placed at the beginning of your program.
This is what i have but the teacher says i need to correct it, i need to programm it so the user chooses to do either the decimal to binary or binary to decimal and then display the results:
The main( ) function should be placed at the beginning of your program.
This is what i have but the teacher says i need to correct it, i need to programm it so the user chooses to do either the decimal to binary or binary to decimal and then display the results:
Code:
#include <iostream> #include <string> #include <math.h> using namespace std; int main() { // Conver a decimal number to binary int dec, len; string bin; // Ask user to enter a decimal numner cout << "Please enter a decimal number:" << endl; cin >> dec; bin = ""; while (dec != 0) { if (dec % 2 == 0) bin.insert(0, "0"); else bin.insert(0, "1"); dec = dec / 2; } // Output decimal number to binary number cout << "The equivalent binary number is: " << bin << endl << endl; // Convert a binary number to decimal double deci; // Ask user to enter a binary number cout << "Enter a binary number:" << endl; cin >> bin; cout << bin << endl; len = (int) bin.length(); cout << len << endl; deci = 0; for (int i=0; i<len; i++) if (bin.at(i) == '1') deci = deci + pow(2., len-i-1); // Output binary number to decimal number cout << "The equivalent decimal number is: " << deci << endl << endl; }
Comment