加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 计算给定更改金额的方式的数量

发布时间:2020-12-16 10:20:26 所属栏目:百科 来源:网络整理
导读:我试图编写一个算法来计算用给定面额制作一定数量的不同可能方式的数量. 假设美元的面额分别为100美元,50美元,20美元,10美元,5美元,1美元,0.25美元,0.10美元,0.05美元和0.01美元.下面的函数,适用于int amount和int denominations /* Count number of ways of
我试图编写一个算法来计算用给定面额制作一定数量的不同可能方式的数量.
假设美元的面额分别为100美元,50美元,20美元,10美元,5美元,1美元,0.25美元,0.10美元,0.05美元和0.01美元.下面的函数,适用于int amount和int denominations

/* Count number of ways of making different combination */
int Count_Num_Ways(double amt,int numDenom,double S[]){
   cout << amt << endl; //getchar();

  /* combination leads to the amount */
  if(amt == 0.00)
    return 1;

  /* No combination can lead to negative sum*/
  if(amt < 0.00)
    return 0;

  /* All denominations have been exhausted and we have not reached
     the required sum */
  if(numDenom < 0 && amt >= 0.00)
    return 0;

  /* either we pick this denomination,this causes a reduction of 
     picked denomination from the sum for further subproblem,or 
     we choose to not pick this denomination and 
     try a different denomination */
   return Count_Num_Ways(amt,numDenom - 1,S) + 
          Count_Num_Ways(amt - S[numDenom],numDenom,S);
}

但是当我将逻辑从int更改为float时,它会进入无限循环.我怀疑这是因为代码中的浮点比较.我无法弄清楚无限循环行为的确切原因.
在这方面的任何帮助都会有所帮助.

解决方法

当处理这种“小”货币金额而不处理利息时,仅仅处理美分和整数金将更容易,而不是使用浮点数.

所以只需改变你的公式,使用美分而不是美元,并继续使用整数.然后,当你需要显示金额时,只需将它们除以100即可获得美元和模数100来获得美分.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读