gpt4 book ai didi

C 编程 - 分解金钱

转载 作者:行者123 更新时间:2023-12-01 15:07:03 24 4
gpt4 key购买 nike

我需要在他们各自的钞票/硬币上 segmentation 金额。

输出有点像这样:

到目前为止,这是我的代码:(我将最后几段代码作为注释,因为错误来自那里)

  { 
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;
}

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

谢谢!

最佳答案

这是一个简单的启发式问题。你已经有了正确的想法。首先,如果您想使用 int(这可能是避免 fp 精度问题和使用单独 fmod 的需要的好主意),您必须缩放浮点输入和模数/除数除以 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;
}

[编辑] 如果您在理解指针方面有困难,那么就按照您编写的方式进行操作,而不使用 units 函数,但相应地修改它以读入 float 并乘以 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);

...
}

关于C 编程 - 分解金钱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3126696/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com