【问题标题】:Not counting all the coins不算所有的硬币
【发布时间】:2014-09-18 02:53:14
【问题描述】:

我正在尝试创建一个简单的变更分类程序,一切正常,预计检测季度的部分除外。

电流输出示例:

The amount you entered is: 52.50

You have this many Fifty dollars: 1 

You have this many Ten dollars: 0

You have this many One: 2

You have this many Quarters: 0

期望的输出:

The amount you entered is: 52.50

You have this many Fifty dollars: 1 

You have this many Ten dollars: 0

You have this many One: 2

You have this many Quarters: 2

代码:

#include <iostream>

using namespace std;

const int FIFTY = 50;
const int TEN = 10;
const int ONE = 1;
const double QUARTER = 0.25;

int _tmain(int argc, _TCHAR* argv[])
{
    int change;

    cout << "Enter the amount of money in your wallet: ";
    cin >> change;
    cout << endl;


    cout << "The amount you entered is: " << change << endl;
    cout << "The number of Fifty dollars to be returned is: " << change / FIFTY << endl;
    change = change % FIFTY;

    //
    cout << "The number of Ten dollars to be returned is: " << change / TEN << endl;
    change = change % TEN;

    //
    cout << "The number of One dollars to be returned is: " << change / ONE << endl;
    change = change % ONE;

    //
    cout << "The number of Quarters to be returned is: " << change / QUARTER << endl;
    change = change % QUARTER;

    return 0;
}

我遇到的两个错误是:

Error   1   error C2297: '%' : illegal, right operand has type 'double' 

Error2  IntelliSense: expression must have integral or unscoped enum type   

【问题讨论】:

  • 我的建议是您使用美分而不是美元作为单位。这样您就不必处理非整数类型了。
  • 如果将所有内容都转换为美分,则可以避免此问题。
  • 为了进一步澄清,FIFTYTENONE 都是整数,但 QUARTERSdouble (0.25)。除以浮点值时,尝试取余数是没有意义的。
  • change = change % QUARTER; 无效,因为 QUARTER 是 0.25,它不是整数。你可以说change -= QUARTER * (change / QUARTER);。请注意,当使用浮点类型(此处为 double)时,通常会出现微小的舍入误差,因此之后 change 可能不完全为 0。
  • 那么有没有更好的方法来创建这样的程序?它必须是美元,只有一个硬币的价值,那就是硬币。我会从头开始,因为这条路似乎走错了路。

标签: c++ double modulo


【解决方案1】:

您的change 变量是int 类型,因此它根本不会存储52.50

它将读取52然后停止。

除此之外,您不能在 % 运算符中使用浮点值。

我建议读取双精度值,将其乘以 100,也许添加一个小增量(如 0.001)以避免潜在的浮点精度问题,然后将其放置变成int。换句话说,使它成为整数美分。

然后使用int 进行计算。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 2016-07-04
    相关资源
    最近更新 更多