Ignat Ospadov Ignat Ospadov - 3 months ago 7
C Question

Unexpected value when performing simple arithmetic on int that was assigned a rounded float value in C

Hours of trying to figure this out have led to nowhere. I don't understand why the integer value of nickels is so high?

Please enter amount of change owed in $xx.xx format: $10.73
1073
Quarters: 42, remainder: 23
dimes: 2, remainder: 3
nickels: 4195856, remainder: 3
pennies: 3

#include <stdio.h>
#include <math.h>

int main ()
{

float userinput;
int cents, count, quarters, dimes, nickels, pennies, remainder;

printf("Please enter amount of change owed in $xx.xx format: $");
scanf("%f",&userinput);

while ((userinput <= 0) || (userinput < 0.01))
{
printf("Please enter a value equal to or greater than $0.01: $");
scanf("%f",&userinput);
}

cents = roundf(userinput * 100);
printf("%d\n", cents);

while ((cents / 25) >= 1) {

quarters = cents / 25;
remainder = cents % 25;
break;
}

printf("Quarters: %d, remainder: %d\n", quarters, remainder);

while ((remainder / 10) >= 1) {

dimes = remainder / 10;
remainder = remainder % 10;
break;
}

printf("dimes: %d, remainder: %d\n", dimes, remainder);

while ((remainder / 5) >= 1) {

nickels = remainder / 5;
remainder = remainder % 5;
break;
}

printf("nickels: %d, remainder: %d\n", nickels, remainder);

while ((remainder / 1) >= 1) {

pennies = remainder / 1;
break;
}

printf("pennies: %d\n", pennies);
}

Answer

You need to initialize your variables.

while ((remainder / 5) >= 1) {   // If "(remainder / 5) >= 1" is false

    nickels = remainder / 5;     // nickles is never set
    remainder = remainder % 5;
    break;
}

printf("nickels: %d, remainder: %d\n", nickels, remainder);  // Use of uninitialized value -> UB

So try to do:

int cents=0, count=0, quarters=0, dimes=0, nickels=0, pennies=0, remainder=0;

In general I think you should use if instead of while

int nickels = 0;

....
....

if ((remainder / 5) >= 1) {

    nickels = remainder / 5;
    remainder = remainder % 5;
}

BTW: When using scanf always check the return value.

Comments