在C问题中将Double转换为Int

时间:2011-02-16 01:36:39

标签: c int double

int main(void)
{
    double dollars;
    int count;

    /* Get amount of money and make sure it's in range */
    printf("Enter an amount up to $100.00: ");
    scanf("%lf",&dollars);
    while(dollars <= 0 || dollars > 100) {
        printf("Re-enter an amount: ");
        scanf("%lf",&dollars);
    }

    /* Convert money to 2 decimal places */
    dollars = (int) (dollars * 100) / 100.00;
    printf("\nAmount entered: $%.2lf\n\n", dollars);
    printf("Change breakdown:\n");

    /* Determine amount of $20.00s */
    count = dollars / 20;
    if(count > 1)
        printf("%i $20.00s\n", count);
    else if(count == 1)
        printf("%i $20.00\n", count);
    dollars = dollars - (count * 20);

    /* Determine amount of $10.00s */
    count = dollars / 10;
    if(count > 1)
        printf("%i $10.00s\n", count);
    else if(count == 1)
        printf("%i $10.00\n", count);
    dollars = dollars - (count * 10);

    /* Determine amount of $5.00s */
    count = dollars / 5;
    if(count > 1)
        printf("%i $5.00s\n", count);
    else if(count == 1)
        printf("%i $5.00\n", count);
    dollars = dollars - (count * 5);

    /* Determine amount of $1.00s */
    count = dollars / 1;
    if(count > 1)
        printf("%i $1.00s\n", count);
    else if(count == 1)
        printf("%i $1.00\n", count);
    dollars = dollars - (count * 1);


    /* Determine amount of pennies */
    /* NOT WORKING if 55.41 is inputted count becomes 40 instead of 41 */
    count = dollars / 0.01;
    printf("\n\n%i",count);
    printf("\n%lf\n\n",dollars / 0.01);

    return 0;
}

2 个答案:

答案 0 :(得分:2)

我同意使用整数而不是双打的评论,但快速解决方法是更改​​计算便士的行:

count = dollars / 0.01;

为:

count = round(dollars / 0.01);

答案 1 :(得分:1)

考虑使用整数。他们更容易合作,特别是涉及金钱时。

double input_dollars;
// ...
long dollars = input_dollars * 100 + 0.5;  // in cents