So this program is a simple decimal to binary converter.
I want my code to repeat until user presses ctrl + D
. I also want to let the user know that the number input is not a positive whole number if they put in a number like -2
or 1.1
.
The problem is when they enter a float
my code just infinitely prints my first print statement.
This is my code:
void DecToBin(int userInput){
int binary[32];
int i = 0;
while (userInput > 0) {
binary[i] = userInput % 2;
userInput /= 2;
i++;
}
for (int j = i - 1; j >= 0; --j) {
printf("%d", binary[j]);
}
}
int main(void) {
int userDec;
int res;
while(1) {
printf("Please enter a positive whole number (or EOF to quit): ");
res = scanf("%d", &userDec);
res = (int)(res);
if (res == EOF) break;
else {
if (!((userDec > 0) && (userDec % 1 == 0))) {
printf("Sorry, that was not a positive whole number.\n");
}
else {
printf("%d (base-10) is equivalent to ", res);
DecToBin(userDec);
printf(" (base-2)!");
printf("\n");
}
}
}
printf("\n");
return 0;
}
So when I input something like 11.1
or a negative value it shouldn't accept it and print "Please enter a positive whole number (or EOF to quit)"
in the terminal.
Inputs like 11.0
should be accepted.
So, I what I'm asking is what is wrong with my code that makes it do this, and how should I fix it? Should I use a float
instead?