1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
|
#include "stdafx.h"
#include <iostream>
#include <limits>
#include <math.h>
using namespace System;
using namespace std;
void ConvertByRecursion(long long n);
long long getDecimal();
long long getBinary();
long long BinaryToDecimal(long long);
int main()
{
long long n, result;
char choice;
cout << "Decimal-Binary Conversions By Fedaa Musleh" << endl;
cout << "Welcome to the Decimal to Binary Converter!" << endl;
while (choice != 'Q' || 'q')
{
cout << "Dec2Bin or Bin2Dec or Quit? (D/B/Q): ";
cin >> choice;
if (choice == 'D' || 'd')
{
n = getDecimal();
while (n !=0)
{
ConvertByRecursion(n);
cout << endl << endl;
n = getDecimal();
}
}
else if (choice == 'B' || 'b')
{
n = getBinary();
result = BinaryToDecimal(n);
cout << "\nTherefore the binary value is: " << result << endl;
cout << "\nThanks for using the decimal converter!" << endl;
}
}
cout << "\nThanks for using the Decimal-Binary converter!" << endl;
system("Pause");
return 0;
}
long long getDecimal()
{
long long n;
bool baddata = false;
do
{
baddata = false;
cout << "Please enter your decimal value to convert (0 to quit): ";
cin >> n;
if(!cin.good())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "I could not decipher your input as a decimal value." << endl;
baddata = true;
}
else if (n < 0)
{
cout << "Please enter a non-negative value." << endl;
baddata = true;
}
} while (baddata);
return n;
}
void ConvertByRecursion(long long n)
{
long long r;
long long newval;
r = n % 2;
newval = n / 2;
Console::WriteLine("Decimal {0,12:D} divided by 2 = {1, 12:D} w/Remainder of: {2,3:D} ", n, newval, r);
if (newval > 0)
{
ConvertByRecursion(newval);
}
else
{
cout << "\nTherefore, by recursion, the binary value of " << n << " is: ";
}
cout << r;
}
long long getBinary()
{
long long n;
bool baddata = false;
do
{
baddata = false;
cout << "Please enter your Binary value to convert to Decimal: (0 to Quit). ";
cin >> n;
if (!cin.good())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "I could not decipher your input as a decimal value " << endl;
baddata = true;
}
else if (n < 0)
{
cout << "Please enter a non-negative value." << endl;
baddata = true;
}
} while (baddata);
return n;
}
long long BinaryToDecimal(long long n)
{
long long value = 0, i = 0, binarydigit, position;
while (n != 0)
{
binarydigit = n % 10;
position = pow(2,i);
value = value + binarydigit*position;
n = n/10;
i++;
}
return value;
}
|