首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

这一题怎么写成循环,很简单的题目

2012-02-04 
这一题如何写成循环,很简单的题目#include stdio.hvoidsb(inta){intb,c,d,e,f,g,h,iba/100//求需要多

这一题如何写成循环,很简单的题目
#include <stdio.h>
void   sb(int   a)
{
      int   b,c,d,e,f,g,h,i;
      b=a/100;     //求需要多少百
      c=a%100;     //求十个位
      d=c/50;       //求需要多少个50
      e=(c%50)/20;       //求需要多少个20
      f=((c%50)%20)/10;       //求需要多少个10
      g=(((c%50)%20)%10)/5;         //求需要多少个5
      h=((((c%50)%20)%10)%5)/2;         //求需要多少个2
      i=(((((c%50)%20)%10)%5)%2)/1;       //求需要多少个1
      printf( "%d个一百块\n%d个五十块\n%d个二十块\n%d个十块\n%d个五块\n%d个二块\n%d个一块\n ",b,d,e,f,g,h,i   );


}

void   main()
{
            int   a;
    printf( "请输入你拥有多少钱 ");
            scanf( "%d ",&a);
            sb(a);    
 
}

[解决办法]
unsigned int bill[] = {100,50,20,10,5,2,1,0};

void getBillCount(unsigned int cash, unsigned int bill_value,unsigned int *pCount, unsigned int *pRemaining)
{
assert(bill_value);
*pCount = cash / bill_value;
*pRemaining = cash % bill_value
}

void main()
{
unsigned int total_value;
printf( "请输入你拥有多少钱 ");
scanf( "%d ", &total_value); //输入数据需查错

unsigned int remaining = total_value;

for (int i = 0; ; ++i) //no end condition, will break out
{
unsigned int nCount = 0;
if (bill[i] == 0)
{
break; //we are end of here
}
getBillCount(remaining, bill[i], &nCount, &remaining);

printf( "%d个:%d 元\r\n ",nCount, bill[i]);
}
}

Notepad写的,可能有Bug.

另外题外话,这个算法如果是为了得到最少纸张数不是广适的,比如有25块钱的面值的钞票的话,就不对了. (40块钱的情况). 所以贪婪算法不一定得到最好结果.
[解决办法]
把这个函数换成这个:

void getBillCount(unsigned int cash, unsigned int bill_value,unsigned int *pCount, unsigned int *pRemaining)
{
// assert(bill_value);
*pCount = cash / bill_value;
*pRemaining = cash % bill_value;
}

热点排行