除了一小段棘手的代码之外,一切都按预期工作。计算费用的最后一行。例如,如果你输入105,它表示你输入了1.05美元,这是好的,那么它计算交易费用,给你0.93555美元作为你的实得工资。我只希望它显示到百分之一的地方,无论金额多少,而不是十万分之一。所以它应该显示0.93美元,因为这是现实的。请注意,根据您在开始时输入的整数,有时会正确放置小数,有时会显示第1000位,它会像我不确定要修复的那样搞砸。
#include <iostream>
using namespace std;
int main() {
int cents;
double total;
cout<<"Enter total amount of coins (whole number): "; //Enter any whole number
cin>>total;
cents = total;
cout<<"You entered " << cents / 25 << " quarters";
cents = cents % 25;
cout<<", " << cents / 10 << " dimes";
cents = cents % 10;
cout<<", " << cents / 5 << " nickels";
cents = cents % 5;
cout<<", " << cents / 1 <<" pennies.";
cents = cents % 1;
cout<<" That is " << "$" <<total / 100 << "."<<endl; //Converting to dollar amount
cout<<"After the fee, you take home " << "$" << (total - (0.109 * total)) / 100 << "."; //What you're left with after the fee
答案 0 :(得分:2)
如果您在标题中包含setprecision()
,则可以使用<iomanip>
,然后使用fixed
设置您希望在小数点后显示多少位数。
这些页面解释得非常好:
答案 1 :(得分:1)
在最后一个陈述中,表达式
(total - (0.109 * total)) / 100
应该是:
(total - int(0.109 * total))/100
(在这种情况下,你可以不使用&lt; iomanip&gt;或任何其他附加功能。只需将产品转换为int)
答案 2 :(得分:0)
错误:
预期行为:
追踪错误的可能原因:
最后一行打印带回家费用。所以最后一行可能会导致错误。
最后一行的公式((total - (0.109 * total)) / 100
)取决于变量total
。
只有cin
行(cin >> total;
)和total
(double total;
)的定义会影响变量total
这些都是导致错误的可能原因。
简化程序,其中包含错误的所有可能原因:
#include <iostream>
using namespace std;
int main() {
double total;
// Enter any whole number
cout << "Enter total amount of coins (whole number): ";
cin >> total;
// What you're left with after the fee
cout << "After the fee, you take home " << "$"
<< (total - (0.109 * total)) / 100
<< ".";
}
一些想法:
想法1:要将浮点数向下舍入为整数,只需将其转换为整数。 (例如cout << int(30.10) << "\n";
)
创意2:将浮点数向下舍入到两位小数,将浮点数乘以100,将结果向下舍入为整数,然后除以100.0。
如果这听起来太单调乏味,也可以使用图书馆。见Rounding to 2 decimal points
解决方案:
#include <iostream>
using namespace std;
int main() {
// Enter any whole number
cout << "Enter total amount of coins (whole number): ";
double total;
cin >> total;
// calculate the take home fee without rounding
double take_home_money = (total - 0.109 * total) / 100;
// Round down the take home fee to two decimal places
take_home_money = int(take_home_money * 100) / 100.0;
// What you're left with after the fee
cout << "After the fee, you take home $"
<< take_home_money << ".";
}
另见C++ , A code to get an amount of money to convert into quarters, dimes , nickels, pennies
的答案