C++ 关于小数的投币机

C++ 关于小数的投币机,c++,C++,除了一行小小的乱七八糟的代码外,一切都按预期进行。计算费用的最后一行。例如,如果你输入105,它说你输入了$1.05,这是好的,然后它计算交易费用,给你$0.93555作为你的实得工资。我只想让它显示到第一百位,不管是多少美元,而不是第十万位。所以它应该显示0.93美元,因为这是现实的。请注意,根据您在开始时输入的整数,有时小数点的位置正确,有时显示第千位,这就像是一个我不确定要解决的问题 #include <iostream> using namespace std; int m

除了一行小小的乱七八糟的代码外,一切都按预期进行。计算费用的最后一行。例如,如果你输入105,它说你输入了$1.05,这是好的,然后它计算交易费用,给你$0.93555作为你的实得工资。我只想让它显示到第一百位,不管是多少美元,而不是第十万位。所以它应该显示0.93美元,因为这是现实的。请注意,根据您在开始时输入的整数,有时小数点的位置正确,有时显示第千位,这就像是一个我不确定要解决的问题

#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
#包括
使用名称空间std;
int main(){
整数美分;
双倍总数;
库托塔尔;
美分=总数;

cout如果标题中包含
,则可以使用
setprecision()
,然后使用
fixed
设置小数点后要显示的位数

以下几页很好地解释了这一点:


在最后一条语句中,表达式

(total - (0.109 * total)) / 100 
应该是:

(total - int(0.109 * total))/100
(在这种情况下,您可以不使用或任何其他附加功能,只需将产品转换为int即可)

错误:

  • 带回家的费用并不是只有两位小数。例如:输入105枚硬币,带回家的费用为0.93555
预期行为:

  • 带回家的费用应该四舍五入到小数点后两位。(我假设“公司”想要更多的钱。所以他们想要四舍五入带回家的钱。每一分钱都很重要。)
跟踪错误的可能原因:

#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
         << ".";
}
  • 带回家的费用由最后一行打印。因此,最后一行可能会导致错误

  • 最后一行的公式(
    (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
             << ".";
    }
    
    #包括
    使用名称空间std;
    int main(){
    双倍总数;
    //输入任意整数
    cout>total;
    //交了费用后你还剩下什么
    
    不,这不起作用。0.93555是由代码的最后一行计算出来的,这取决于用户输入的
    total
    ,以及
    total
    double total;
    )的定义。其他行(如
    cent/25.0
    )不应该影响它。你想要向上取整还是向下取整?@RawN这不是问题的开始。他应该用整数来计算美分。谢谢这个成功了-为什么加int会成功?从所有其他的回答中也学到了。谢谢大家!@Smokeyflo如果你将减数转换为整数,那么差异将与分钟数相同。