I want to convert a floating point number like 0.15 -> 15
or 0.4 -> 4
My idea is to
Multiply a number with amount of floating point places.
Floor it.
Cast it to (int).
Can't figure how to do the first step.
Clarification: I have to make a program that uses a greedy algorithm, User enters change_owed. This program would then check for the lowest number of coins possible to give-out.
Code:
#include <ctype.h>
#include <stdio.h>
int main(void)
{
int coins = 0;
float cash_owed = 0;
do
{
printf("Cash owed: ");
scanf("%f" , &cash_owed);
}
while(cash_owed < 0);
while(cash_owed > 0)
{
if(cash_owed >= 0.25)
{
cash_owed -= 0.25;
printf("Cash owed: %f\n", cash_owed);
coins++;
printf("Coins: %d\n", coins);
}
else if(cash_owed >= 0.10)
{
cash_owed -= 0.10;
printf("Cash owed: %f\n", cash_owed);
coins++;
printf("Coins: %d\n", coins);
}
else if(cash_owed >= 0.05)
{
cash_owed -= 0.05;
printf("Cash owed: %f\n", cash_owed);
coins++;
printf("Coins: %d\n", coins);
}
else
{
cash_owed -= 0.01;
printf("Cash owed: %f\n", cash_owed);
coins++;
printf("Coins: %d\n", coins);
}
}
printf("%d\n", coins);
return 0;
}
Not my best design. But it fails on many different examples given below, Acc to my understanding it's due to floating-point arithmetic imprecision.
Fails for: 0.15, 1.6 and 4.2. wherein it skips one or more if statement due to floating-point arithmetic imprecision.
So I devised a new algo which will convert these values to proper int. Like
0.15 -> 15
So I have to work with integers to eliminate that float point errors, If this makes any sense