#include <stdio.h> /*printf and scanf option*/
#include <math.h>
void change(double coin_change, int *quarters, int *dimes, int *nickels, int *pennies); /*function protype*/
int main(void)
{
int fifties = 0, twenties = 0, tens = 0, fives = 0, dollars = 0, quarters = 0, dimes = 0, nickels = 0, pennies = 0;
double amt_paid = 0, amt_due = 0, amt_change = 0, coin_change = 0; /*declared avriables*/
printf("Enter the amount paid> "); /*Prompt user to enter amount paid*/
scanf("%lf", &amt_paid);
printf("Enter the amount due> "); /*Prompt user to enter amount due*/
scanf("%lf", &amt_due);
amt_change = amt_paid - amt_due; /*Formula for amount of change to be given*/
dollars = (amt_change);
coin_change = (int)((amt_change - (amt_change)) * 100 + 0.5);
coin_change = coin_change * 100;
printf("\n%f\n", coin_change);
change(coin_change, &quarters, &dimes, &nickels, &pennies);
printf("Change is fifties: %d$, twenties: %d$, tens: %d$, fives: %d$, dollars: %d$, quarters: %d, dimes: %d, nickels: %d,\
pennies: %d", fifties, twenties, tens, fives, dollars, quarters, dimes, nickels, pennies);
return(0);
}
void change(double coin_change, int *quarters, int *dimes, int *nickels, int *pennies)
{
int q = 1, d = 1, n = 1, p = 1;
do {
if(coin_change >= 25){
*quarters = *quarters + q;
coin_change = coin_change - 25;
}
else if (coin_change >= 10) {
*dimes = *dimes + d;
coin_change = coin_change - 10;
}
else if (coin_change >= 5) {
*nickels = *nickels + n;
coin_change = coin_change - 5;
}
else if (coin_change >= 1) {
*pennies = *pennies + p;
coin_change = coin_change - 1;
}
} while (coin_change >= 1);
}
对不起,我第一次不太清楚。我需要的是创建基本上是收银机程序。当给出应付金额,以及从用户支付的金额时,我应该收到输出,告诉我多少50美元的钞票,20s,10s,5s,1s,quarter,dimes,nickels和pennies我应该收到更改。由于我是编程新手,所以您看到的代码就是我所知的最佳代码。我确实需要改进甚至完全改变它。我真正想做的是找出我的错误并修复它们。我希望尽快完成这些代码。我觉得我很亲密,但只是错过了它。也许我错了,但这就是我要来找你们的。
答案 0 :(得分:1)
有几件事:
fifties
,twenties
,tens
,fives
,dollars
等。这里的行:
coin_change = (int)((amt_change - (amt_change)) * 100 + 0.5);
coin_change = coin_change * 100;
错了。它们应该替换为以下内容:
coin_change = (100 * amt_change)
。
您是否听说过+=
/ -=
运营商?他们会改变这些思路:
*quarters = *quarters + q;
coin_change = coin_change - 25;
进入这个:
*quarters += q;
coin_change -= 25;
修好这些东西后,你的代码运行正常。
答案 1 :(得分:0)
我不想为你编写代码,因为这有点像家庭作业,但这是算法:
read_from_keyboard(amount_due)
read_from_keyboard(amount_paid)
change = amount_paid - amount_due
for each denomination in (
fifties, twenties, tens, fives, ones, quarters, dimes, nickels, pennies) {
while (change >= value of denomination) {
increment counter for denomination
subtract value of denomination from change
}
print counter + name of denomination // Ex: "4 twenties"
}
“技巧”是要意识到你可以用完全相同的方式处理整个美元价值和硬币 - 编程艺术的一部分是能够找到一个可以重复使用的通用解决方案,而不是处理每种情况都是特例。
您可能希望将更改转换为表示以美分为单位的值的整数,因此可以避免浮点运算创建的舍入错误。
祝你好运!