we were asked to turn a binary number to decimal so I did this
#include <iostream>
using namespace std;
int main()
{
int binary, converted = 0;
int number, d = 1;
cout << "Please enter a binary number:";
cin >> binary;
while (binary % 10 != 0 && binary % 10 != 1)
{
cout << "The number you entered is not binary number. Please enter a binary number: ";
cin >> binary;
}
while (binary != 0)
{
number = binary % 10;
converted += number *d;
d *= 2;
binary = binary / 10;
}
cout << "The number converted to decimal>> " << converted;
}
but the problem is when I type a number like 201 or 200 (the last number is 1 or 0) it runs normally when it should give me that it's false. what should I do
read it as a string, check the string for anything not '0' or '1'
then just convert it, without all the modulus stuff, by iterating the string's characters.
the machine will do the work for you.
int result = 0;
for(i … string's length)
i << 1;
i+= string[i]=='1'; //if its a 1 add 'true' which is numeric 1 else add false numeric zero, shift it up and repeat.
Your test is only testing the last digit. You need to test them all. But jonnin's suggestion to read it as a string is a better idea. You should also ensure that the string is not too long.
Using an integer (even a 64-bit unsigned integer) means that the binary input is limited to much less than the limit of the integer. 24 1's (as a decimal value) won't fit into 64 bits even though the decimal equivalent of interpreting it as binary obviously fits into a 24 bits. The highest value you can enter into a 64-bit unsigned integer is 20 1's.
#include <iostream>
int main()
{
using ull = unsignedlonglong;
ull binary = 0;
while (true)
{
std::cout << "Please enter a binary number: ";
std::cin >> binary;
ull test = binary;
while (test && test % 10 < 2)
test /= 10;
if (test == 0)
break;
std::cout << "The number you entered is not binary number\n";
}
ull decimal = 0;
for ( ; binary; binary /= 10)
decimal = decimal * 2 + binary % 10;
std::cout << "The number converted to decimal: " << decimal << '\n';
}
Hello and thank you for everyone who replied. I was thinking about solving it with string but the problem is that we were asked to only use things we learned and we haven't learned string yet. Is there any other way I could do that without string?
you have not read text input from the keyboard yet with a cin statement?
what you have works for 20 bits which is enough to work with. You just have a logic problem to debug --- see the comment after mine that you are only checking 1 digit for valid, not the whole number. You need to extract the digits and check each digit, is all.
Thank you jonnin and FurryGuy for the help! We have been taught about arrays and I ended up using string because I couldn't find a better way. Thank you all for the help.