C编程 - 打破钱

时间:2010-06-27 07:29:29

标签: c

我需要分解各自账单/硬币的金额。

输出有点像这样:

到目前为止,这是我的代码:(我在最后几个代码中做了一个评论' 错误来自那里)

  { 
  int x,y;

  printf("Enter input: ");
  scanf("%d",&x);

  y=x/1000;
  printf("\n# of $1000 bill: %d",y);
  x = x%1000;

  y=x/500;      
  printf("\n# of 4500 bill: %d",y);    
  x = (x%500);

  y=x/200;
  printf("\n#. of $200 bill: %d",y);    
  x = (x%200);

  y=x/100;
  printf("\n# of $100 bill: %d",y);    
  x = (x%100);

  y=x/50;
  printf("\n# of $50 bill: %d",y);    
  x = (x%50);

  y=x/20;
  printf("\n# of $20 bill: %d",y);    
  x = (x%20);

  y=x/10;
  printf("\n#. of $10 coin: %d",y);    
  x = (x%10);

  y=x/5;
  printf("\n#. of $5 coin: %d",y);    
  x = (x%5);

  y=x/1;
  printf("\n# of $1 coin: %d",y);    
  x = (x%1);


  getch();
  return 0;
  }

我希望你能帮我解决这个问题。 :/

谢谢!

2 个答案:

答案 0 :(得分:6)

这是一个简单的启发式问题。你已经有了正确的想法。首先,如果你想使用int(在你的情况下这可能是一个好主意,以避免fp精度问题和需要使用单独的fmod),你将不得不缩放浮点输入和你的模数/ divisors by 100.另外,为了减少一些冗余,请考虑使用如下函数:

// returns number of units and subtracts unit_size * result
// from val
int units(int* val, int unit_size)
{
    int num = *val / unit_size;
    *val %= unit_size;
    return num;
}

printf("No. of P1000 bill: %d\n",units(&x, 1000 * 100) );
printf("No. of P500 bill: %d\n",units(&x, 500 * 100) );
printf("No. of P200 bill: %d\n",units(&x, 200 * 100) );
etc.

这应该会减少冗余代码。也许不值得过于花哨,我怀疑这是功课。完整的解决方案:

// returns number of units and subtracts unit_size * result
// from val
int units(int* val, int unit_size)
{
    int num = *val / unit_size;
    *val %= unit_size;
    return num;
}

int main()
{
    printf("Enter input: ");

    float amount;
    scanf("%f",&amount);
    int x = (int)(amount * 100.0 + 0.5);

    printf("No. of P1000 bill: %d\n", units(&x, 1000 * 100) );
    printf("No. of P500 bill: %d\n", units(&x, 500 * 100) );
    printf("No. of P200 bill: %d\n", units(&x, 200 * 100) );
    printf("No. of P100 bill: %d\n", units(&x, 100 * 100) );
    printf("No. of P50 bill: %d\n", units(&x, 50 * 100) );
    printf("No. of P20 bill: %d\n", units(&x, 20 * 100) );
    printf("No. of P10 coin: %d\n", units(&x, 10 * 100) );
    printf("No. of P5 coin: %d\n", units(&x, 10 * 100) );
    printf("No. of P1 coin: %d\n", units(&x, 1 * 100) );
    printf("No. of 25 cents: %d\n", units(&x, 25) );
    printf("No. of 1 cent: %d\n", units(&x, 1) );

    return 0;
}

[编辑]如果您无法理解指针,那么只需按照您不使用单位函数的方式进行操作,而是相应地修改它以读取浮点数并乘以100,如上例所示。

[编辑]要求:

int main()
{
    printf("Enter input: ");

    float amount;
    scanf("%f",&amount);
    int x = (int)(amount * 100.0 + 0.5); // x stores the user input in cents

    int y = x / 100000; // 1000 dollars is 100,000 cents
    printf("\nNo. of P1000 bill: %d",y);
    x = x % 100000;

    ...

    y=x / 25; // we're working with cents, so 25 = 25 cents
    printf("\nNo. of 25 cents: %d",y);    
    x = (x % 25);

    ...
}

答案 1 :(得分:2)

将用户的值扫描到float,然后将美元和美分分成两个int值。

美分值所需的硬币应该很容易计算,使用你已经使用的相同方法(除了将25分为25分,1分为1分等)。