我正在尝试制作一个提供最少硬币数量的程序,但如果我提供的数字不是分成四等份的数字,它就会惨遭失败。例如,如果我输入 1.25,我得到 5 个四分之一,但如果我输入 1.26,我得到 5 个四分之一 1 镍,这当然是不正确的。我究竟做错了什么?
#include <stdio.h>
#include <cs50.h>
#include <math.h>
void calculate_change(change_requested){
int num_quarters = 0;
int num_dimes = 0;
int num_nickles = 0;
int num_pennies = 0;
int val_quarters = 25;
int val_dimes = 10;
int val_nickles = 5;
num_quarters = floor(change_requested/val_quarters);
if(change_requested % val_quarters != 0){
num_dimes = floor( (change_requested - (num_quarters * val_quarters))/val_dimes );
if( change_requested - (((num_quarters * val_quarters) + (num_dimes * val_dimes))) != 0){
num_nickles = floor( change_requested - ( (num_quarters * val_quarters) + (num_dimes * val_dimes)/val_nickles ));
if( change_requested - (((num_quarters * val_quarters) + (num_dimes * val_dimes) + (num_nickles * val_nickles))) != 0){
for(int i = 0; i<change_requested - (((num_quarters * val_quarters) + (num_dimes * val_dimes) + (num_nickles * val_nickles))); i++){
num_pennies++;
}
}
}
}
if(num_quarters > 0){
printf("%i Quarters ",num_quarters);
}
if(num_dimes > 0){
printf("%i Dimes ",num_dimes);
}
if(num_nickles > 0){
printf("%i Nickles",num_nickles);
}
if(num_pennies > 0){
printf("%i Pennies",num_pennies);
}
printf("\n");
}
int main (void){
printf("How Much Change Do You Need?\nAmount: ");
float change_requested = GetFloat();
calculate_change(change_requested * 100);
return 0;
}