收银员功能不适用于特定情况

时间:2014-07-02 08:33:30

标签: c++

这是我第一次在这里发帖,所以如果代码太长,我会非常乐意编辑它。

我正在制作收银员,这是一种改变的功能。

奇怪的是: 如果我为1.15购买1.14,我会得到一分钱。 但是,如果我为.15购买.14,我就没有回头了。

另外,如果我为.20购买.15,我会买回镍。 但是,如果我以.25购买.20,我会得到4便士。我需要帮助理解为什么我得到四便士而不是0便士和1镍就像我应该的那样。我相信在某个地方划分某些事情是错误的。

#include <iostream>
#include <cmath>

using namespace std;

int main() {

  double buyAmount = 0.0;
  double paidAmount = 0.0;
  double diffAmount = 0.0;
  double smallChange = 0.0;
  int dollars = 0;
  int quarters = 0;
  int dimes = 0;
  int nickels = 0;
  int pennies = 0;

  cout << "Enter purchase amount: ";
  cin >> buyAmount;
  cout << endl;

  cout << "Enter paid amount: ";
  cin >> paidAmount;
  cout << endl;

  diffAmount = paidAmount - buyAmount;

  if (diffAmount < 0 ) {
     cout << "Error: Make sure paid amount exceeds purchase amount. ";
     cout << endl;
  }

  dollars = floor(diffAmount);
  smallChange = (diffAmount - dollars) * 100  

  quarters = (smallChange / 25);
  smallChange = smallChange - (quarters * 25);
  dimes = (smallChange / 10);
  smallChange = smallChange - (dimes * 10);
  nickels = floor(smallChange / 5);
  smallChange = smallChange - (nickels * 5);
  pennies = floor(smallChange / 1); 

  cout << "Total Change: $" << diffAmount;
  cout << endl << endl;
  cout << "dollars " << dollars << endl;
  cout << "quarters " << quarters << endl;
  cout << "dimes " << dimes << endl;
  cout << "nickels " << nickels << endl;
  cout << "pennies " << pennies << endl;
}

2 个答案:

答案 0 :(得分:0)

浮点运算并不准确。有时你得到的错误很少。例如0.25 / 0.25可导致1或0.99999999999999 如果您使用地板,除非您添加额外的“epsilon”,否则无法使用地板。补偿计算错误,例如

quarters = floor(smallChange / 0.25);

可能会成为

const double epsilon = 1E-5;
quarters = floor(smallChange / 0.25 + epsilon);


管理货币仍然是一个更好的主意:

int diffAmount = ...; // (pennies or cents).
int dollars = diffAmount / 100;
int smallChange = diffAmount % 100;
int quarters = smallChange / 25;
smallChange -= quarters * 25;
int dimes = smallChange / 10;
smallChange -= dimes * 10;
...

您还应该对数据进行驱动:创建包含不同硬币及其值的数据结构,然后编写代码以循环该数据结构。这样可以轻松切换到另一种货币(大多数不会有四分之一硬币)或修复错误。

答案 1 :(得分:0)

你不应该使用浮点,因为它们不准确。

相反,将美元和美分分别读入整数,然后完全转换为美分 整数除法将使这项工作完美无缺 如果您只是假设用户输入正确,您可以这样读:

int purchaseDollars = 0;
int purchaseCents = 0;
char decimalPoint;  // Can be anything except a number in this snippet.
std::cin >> purchaseDollars >> decimalPoint >> purchaseCents;
int buyAmount = purchaseCents + 100 * purchaseDollars; // Convert to cents
// Same for paid amount

int diffAmount = paidAmount - buyAmount;
int dollars = diffAmount / 100;   // Integer division makes this work as you want
diffAmount -= dollars;            // Now diffAmount is just the cents
/// and so on...