该代码无法正常运作!! 我是C ++的新手,我的编写代码从用户那里获取价值(金额),然后将其转换为“季度= 25美分,硬币= 10美分,镍币= 5美分,便士= 1美分” 所以例如当我输入值7.47时我应该得到29个季度,2个角钱,0个镍币,2个便士等等...... 我的问题是,我已经尝试了很多值,它工作得很好,但当我尝试值9.53我应该得到38个季度,0角钱,0个镍币和3个便士,但我得到38个季度,0角钱,0个镍币和2个便士 当我尝试8.53时会发生同样的错误,但是当我尝试6.53,5.53 .4.53时效果很好!!我现在很困惑,所以请帮助!!
`#include<iostream>
using namespace std;
int main()
{
double money, c_money, quarters, dimes, nickels, pennies, remainder; char response;
new_input:
cout << " Enter the amount of money to be converted : " << endl;
cin >> money;
while (money < 0)
{
cout << " Invalid input , please enter a non-negative value " << endl;
cin >> money;
}
c_money = money * 100;
quarters = (int)c_money / 25;
remainder = (int)c_money % 25;
dimes = (int)remainder / 10;
remainder = (int)remainder % 10;
nickels = (int)remainder /5;
remainder = (int)remainder % 5;
pennies = (int)remainder ;
cout << endl;
cout << " The amount of money entered could be represented as : " << endl;
cout << "*****************************************************" << endl;
cout <<" Number of quarters : "<< quarters << endl;
cout <<" Number of dimes : "<<dimes << endl;
cout <<" Number of nickels : "<< nickels << endl;
cout <<" Number of pennies : "<< pennies << endl<<endl;
cout << "Do you want to enter more values ?? type , y or n and press Enter ! " << endl;
cin >> response;
if (response == 'y')
{
goto new_input;
}
else { cout << " Thanks for using our app !! " << endl << endl; }
return 0;
}`
答案 0 :(得分:3)
您是double
不准确的受害者。您的代码可能在99%的情况下有效,但不准确性来自剩余的1%......
我建议您在需要进行精确计算时不要使用double
,例如关于每一分钱都很重要的钱。用int
替换它,将它乘以100(这样你就不会丢失小数部分)并用整数进行所有计算,你会更好。