Reputation: 2003
I have to make a project that consists of calculating the amount of coins you need to form a number. You have quartes, dimes, nickels and pennies and you need to form a number with the least number of coins possible. The number you need to form is prompted to the user.
This is very simple in Python(I implement a function to do something quick):
def calculate_change(change):
count = 0
change*=100
change = int(change)
if change // 25 != 0:
count = change // 25
change = change % 25
if change // 10 != 0:
count += change // 10
change = change % 10
if change // 5 != 0:
count += change // 5
change = change % 5
if change // 1 != 0:
count += change // 1
print count
calculate_change(73)
Now, to implement this in C, I'm having some troubles. I don't quite understand how to change the float the user prompted. I need to convert it first to double, multiply by 100 and then convert to an int but I'm having troubles with it. This is what I wrote for that:
int main(void)
{
float n;
do
{
printf("Change you need: ");
n = GetFloat();
}
while (n < 0);
n = floorf(n * 100 + 0.5) / 100;
int change = (int) n;
change = change * 100;
int count = 0;
if (change / 25 != 0)
{
count = change / 25;
change = change % 25;
}
if (change / 10 != 0)
{
count = count + change / 10;
change = change % 10;
}
if (change / 5 != 0)
{
count = count + change / 5;
change = change % 5;
}
if (change / 1 != 0)
{
count = count + change / 1;
change = change % 1;
}
printf("%d\n", count);
}
Is there something wrong with the conversion from floats to ints in C ? The program returns incorrect results (always 0) when user prompts a number between 0 and 1.
Thanks !
Upvotes: 1
Views: 4176
Reputation: 206667
Problem
When n = 0.5
,
floorf(n * 100 + 0.5) / 100 = floorf(50.5)/100 = 50/100 = 0.5
Hence, the statement
n = floorf(n * 100 + 0.5) / 100;
does not change the value of n
. Now, when you execute:
int change = (int) n;
change
is set to 0
. That explains why you get 0
for most values of n
between 0.0-1.0
.
Solution
I would replace the following lines:
n = floorf(n * 100 + 0.5) / 100;
int change = (int) n;
change = change * 100;
with
n = floorf(n * 100 + 0.5); // Just to make sure rounding occurs properly.
// Thanks to Mark Ransom.
int change = (int) n;
Upvotes: 3
Reputation: 11
You are right that you need to multiply by 100 and then convert to an int, and that's what you're doing in the python code, but in your C code you are doing it backwards - first converting to an int and then multiplying by 100:
int change = (int) n;
change = change * 100;
That (int) cast truncates values to the next lowest integer, so values of n between 0 and 1 will always get set to 0.
Moving the multiplication by 100 ensures that you convert from dollars (e.g. 0.56) to a floating point representation of cents (e.g. 56.0) before converting to an integer of cents e.g. (56):
int change = (int) (n * 100);
Upvotes: 1