不算所有硬币

时间:2014-09-18 02:53:15

标签: c++ double modulo

我正在尝试创建一个简单的更改排序程序,一切都正常运行,期望用于检测季度的部分。

当前输出示例:

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   

1 个答案:

答案 0 :(得分:0)

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

它会读取52然后停止。

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

我建议将读取值作为double,将其乘以100,或者添加一个小的delta(如0.001),以避免潜在的浮点精度问题,然后将其放入int。换句话说,将其作为整数分数。

然后使用int进行计算。