易百教程

使用整数值作金钱计算

由于潜在的舍入,浮点变量不适合涉及金钱的计算。可以使用long整数来存储美分和美元。

#include <stdio.h>

int main(void)
{
    const long unit_price = 350L;                        // Unit price in cents
    int quantity = 0;
    printf("Enter the number that you want to buy:");    // Prompt message
    scanf(" %d", &quantity);                             // Read the input

    long discount = 0L;                                  // Discount allowed
    if(quantity > 10)
      discount = 5L;                                     // 5% discount
    long total_price = quantity*unit_price*(100-discount)/100;
    long dollars = total_price/100;
    long cents = total_price%100;
    printf("\nThe price for %d is $%ld.%ld\n", quantity, dollars, cents);
    return 0;
}

上面示例代码,执行结果是:

hema@ubuntu:~/book$ gcc -o main main.c
hema@ubuntu:~/book$ ./main
Enter the number that you want to buy:3

The price for 3 is $10.50