|
-
April 18th, 2012, 01:55 PM
#1
Newbie questions about bloated binary to decimal converter
Hi all, I'm new to programming and I'm having some minor difficulties with a console app I've made to convert a given binary number into decimal. This program is probably ugly and ultra bloated, so I would gladly accept advice on that front, but keep in mind that we're only using pretty basic stuff. We're not even allowed to use strings.
Basically I have 2 questions.
1. Because of how limited integers are in terms of storage, the largest binary number i can give seems to be 1 111 111 111. Anything larger breaks the program. Is there any way to increase the largest input I can give without completely rewriting the program? I tried changing the num/numCounter (and the typecasting) to long doubles in a blind hope that that would, help, but it just messed stuff up (or I did).
2. I'd also like to make it so that if someone inputs a non-binary number my program tells them so and stops. I figured a switch statement within the while loop would work (for when numCounter/divisor is negative or greater than 1), but I was wondering if instead it was possible to use an if statement that could break the while loop? Any other suggestions?
Anyway, here's the code:
Code:
#include <QtCore/QCoreApplication>
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <cmath>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
char again;
cout<<"This program will convert a binary number into decimal form."<<endl<<endl;
do
{
int numDigits, divisor, ans=0;
int num, numCounter;
cout<<"Please enter the binary number."<<endl;
cin>>num;
numCounter = num;
numDigits = static_cast<int>(1 + log10((static_cast<double>(num))));
divisor = static_cast<int>(pow(10,(static_cast<double>(numDigits) - 1)));
while(divisor >= 1)
{
if((numCounter/divisor)==1)
{
ans = ans + pow(2,(static_cast<double>(numDigits)-1));
numCounter -= divisor;
}
divisor /= 10;
numDigits -= 1;
}
cout<<endl<<num<<" in decimal form is "<<ans<<endl<<endl
<<"Convert another number? (Y)es or (N)o."<<endl;
cin>>again;
cout<<endl<<endl<<endl;
}while(toupper(again) == 'Y');
return a.exec();
}
Thanks to anyone who bothered to look at this. I'm sure it's an eyesore.
Last edited by getajob92; April 18th, 2012 at 02:48 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|