在 C 中将浮点数打印为金钱回报

Print float as money payback in C

我有模拟非接触式结账的 C 代码。

Enter value of your bill: 50
Insert money for payment: 50 20 5 0.10 0
You have inserted: 75.1
To return: 25.1

我必须做到这一点:

Collect your payback: 20 5 0.10

我只能使用这个标称值:

float allowedMoney[13] = {100, 50, 20, 10, 5, 2, 1, 0.50, 0.20, 0.10, 0.05, 0.02 , 0.01};

知道怎么做吗? 非常感谢

main() 函数

int main() {
    float bill = getBill();

    float payment = insertPayment();

    if(!payment) return 1;

    printf("You have inserted: %g\n", payment);


    if(payment < bill) {
        printf("Not enough money!\n");
        return 1;
    }

    float toReturn = payment - bill;
    printf("To return: %g\n", toReturn);

    if(toReturn > 0) {
        int payback = getPayback(toReturn);
        print ... (HELP)    
    }
    return 1;
}

编辑: 例如,我有带值的变量:25.1

我必须在一行中输出:20 5 0.10 那就是“20 美元 + 5 美元 + 10 美分” 我必须将数字 25.1 转换为这样的美元和美分格式:20 5 0.10

20 5 0.10

20 + 5 + 0.10 但没有 +

一般来说,不要使用 float 类型来表示货币。它们很容易出现舍入错误,它们不能准确地表示大数,并且仅仅为了能够得到小数点后的东西可能不值得付出努力。相反,使用整数类型来表示便士或美分的数量,并使用类似这样的方式打印值:

printf("$%d.%02d", amount/100, amount%100);

如果你想表示非常大的数字,你总是可以使用 long long 而不是 int。一个普通的 32 位整数可以表示 $21,474,836.47,而一个 IEEE float32 不能表示 $167,772.17。

你的问题是,"how do I keep prompting for payment until it's greater than or equal to the bill?"

如果是这样,将下面的代码(大约)包装在一个循环中 (while) control

所以:

float payment = insertPayment();

if(!payment) return 1;

printf("You have inserted: %g\n", payment);


if(payment < bill) {
    printf("Not enough money!\n");
    return 1;
}

变成类似:

while(payment < bill)
{
    printf("Not enough money!\n");
    float payment = insertPayment();

    printf("You have inserted: %g\n", payment);

 }