【问题标题】:Converting Double to Int in C Problem [closed]在 C 问题中将 Double 转换为 Int [关闭]
【发布时间】:2011-02-16 01:36:38
【问题描述】:
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;
}

【问题讨论】:

  • 这是作业吗?阅读:cs.tut.fi/~jkorpela/round.html
  • 您的问题是什么?到目前为止,您是如何解决问题的?
  • 是的,我已经坚持了很长时间,试图让双精度转换为正确的整数
  • 看代码中的最后一条注释
  • 我建议不要使用doubles。使用int 并存储美分数。要读取/写入美元金额,您可以编写自己的函数。

标签: c int double


【解决方案1】:

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

count = dollars / 0.01;

到:

count = round(dollars / 0.01);

【讨论】:

    【解决方案2】:

    考虑使用整数。他们更容易合作,尤其是在金钱方面。

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

    【讨论】:

      猜你喜欢
      • 2020-11-05
      • 2014-07-08
      • 2012-06-01
      • 1970-01-01
      • 2016-07-24
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      • 2011-05-10
      相关资源
      最近更新 更多