【发布时间】:2018-06-23 18:29:27
【问题描述】:
这是一个我急需指导的收银员计划。该程序获取物品的成本和为该物品支付的金额,并计算要返还给客户的剩余“零钱”。但是,我遇到了一些我无法解决的问题。第一个是在一定的金额上,exp: cost= 0.25,paid= 100.00,程序会吐出一个 nickle,而应该没有 nickle 用于改变。第二个问题是为 cout 提供的参数:只有个别美元(二十、十、五、一)和硬币(25美分硬币、10美分硬币、5 美分硬币、1 美分硬币)只有当它们出现在零钱中时才可以 cout。没有 0 20 0 10 等等... 所需示例:成本 = 0.25,已支付 = 100.00 将是 4 二十(s) 1 十(s) 1 五(s) 4 个 3 个季度;硬币、镍和便士不应该显示,因为它们是 0。我是否只剩下大量的 If 语句,或者还有其他我可以做的事情吗?也许切换?我不确定,因为我还是个新手。
源代码:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
float purchase, payment, change;
int new_change, one_dollar, five_dollar, ten_dollar, twen_dollar;
int quarter, nickel, dime, penny;
// Program explanation
cout << "This program calculates the change of a payment\n";
cout << "towards a purchase." << endl << endl;
// user prompt to input item cost and
cout << "- - Enter the following Information - -" << endl;
cout << endl << "Cost of Item: $";
cin >> purchase;
cout << endl << endl << "Payment: $";
cin >> payment;
// calculating the balance that is owed back to customer
change = (payment - purchase) * 100;
// this assignment used so that we can use modulo
new_change = ceil(change);
// Following equations used to retrieve respective bill
// amounts owed back to purchaser
twen_dollar = new_change / 2000;
ten_dollar = (new_change % 2000) / 1000;
five_dollar = (new_change % 1000) / 500;
one_dollar = (new_change % 500) / 100;
// Following equations used to retrieve respective coin
// amounts owed back to purchaser
quarter = (new_change % 100) / 25;
dime = (new_change % 25) / 10;
nickel = (new_change % 10) / 5;
penny = new_change % 5;
cout << endl << change << " " << new_change << " " << twen_dollar << "
twenty " << ten_dollar << " ten ";
cout << five_dollar << " five " << one_dollar << " one " << quarter;
cout << " quarter " << dime << " dime " << nickel << " nickel ";
cout << penny << " penny ";
return 0;
}
cout 格式不是最终格式,我在 cout 上显示了“change”和“new_change”,因为在“new_change = change”分配期间我遇到了数字减少的另一个问题; ceil(change) 似乎已经修复了它。欢迎任何建议和批评,只要它们具有建设性。感谢您的宝贵时间。
【问题讨论】:
-
您尝试过怎样调试每个问题?也许您想拆分计算并编写一些自动化测试?这可能会帮助您在不引入新错误的情况下逐个修复错误
-
您可能希望使用编程语言来标记您的问题,以便在 SO 上针对正确的受众。阅读此内容How to debug small programs (#2) 可能也会有所帮助。