2011-02-16 81 views
1
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; 
} 
+1

這是家庭作業?閱讀此:http://www.cs.tut.fi/~jkorpela/round.html – pyon 2011-02-16 01:37:23

回答

1

考慮使用整數。他們更容易合作,特別是涉及到金錢時。

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

我同意使用整數,而不是雙打的評論,但一個快速的解決辦法是改變從計算便士行:

count = dollars/0.01; 

到:

count = round(dollars/0.01);