Reputation: 2144
This is a simple problem of calculating the min number of coins needed to give the change, given a N value. The division 0.04/0.01 gives 3, why?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int MinQtdCoins(float N, float coins[], int qtdCoins)
{
int i, qtdMinCoins = 0;
int numCoins=0;
for(i=0; i<qtdCoins; i++)
{
if(N > coins[i] || fabs(N - coins[i]) < 0.0000000001) // N >= coins[i]
{
numCoins = (int)(N/coins[i]);
printf("Number of Coins: %f divided by %f = %d, ",N,coins[i],numCoins);
qtdMinCoins += numCoins;
N = N - numCoins*coins[i];
printf("remains: %f\n",N);
}
}
return qtdMinCoins;
}
int main()
{
int qtdCoins = 5;
float coins[] = {0.50, 0.25, 0.10, 0.05, 0.01};
float N=9.79;
printf("\n\n%d\n",MinQtdCoins(N, coins, qtdCoins));
return 0;
}
Upvotes: 0
Views: 332
Reputation: 908
you are doing floating point division and keeping the value in an integer...because of this value is truncated to 3
Upvotes: 0
Reputation: 32576
The division 0.04/0.01 gives 3, why?
numCoins = (int)(N/coins[i]);
Casting to int
just truncates fractional part. So if 0.04/0.01 == 3.999..
(due to rounding), the result is 3
.
Upvotes: 5