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