【问题标题】:Could some one find the error in this code?有人能在这段代码中找到错误吗?
【发布时间】:2017-09-10 01:46:48
【问题描述】:

我已经编写了这个程序,当我运行它并输入 20.14 时,这是输出:

输入金额:20.14 更改到期:

20 美元 0 个宿舍 1角钱 0 镍币 3便士

应该是 4 便士。但它显示3。 这是另一个输出:

输入金额:79.58 更改到期:

79 美元 2个季度 0 毛钱 1 镍币 3便士

但是由于某种原因,这里算对了。

谁能帮我找出错误? 提前致谢。

代码如下:

//Description: This program takes in a dollar amount from the user and
//and calculates and displays how to make the change using the smallest
//number of bills and coins possible.

#include <iostream>
using namespace std;

int main()
{
    //Declaring the variables.
    //dollarAmount is the amount that will be input by the user, which
    //will be split into dollars, quarters, dimes, nickels, pennies.

    float dollarAmount;
    int dollars = 0, quarters = 0, dimes = 0, nickels = 0, pennies = 0;

    //Displaying message to user to input value for dollarAmount.

    cout << "Enter the amount: ";

    //Taking in the value for dollarAmount.

    cin >> dollarAmount;

    //Splitting the dollarAmount into dollars, quarters, dimes,
    //nickels and pennies.

    pennies = dollarAmount * 100.0;
    dollars = pennies / 100;
    pennies = pennies % 100;
    quarters = pennies / 25;
    pennies = pennies % 25;
    dimes = pennies / 10;
    pennies = pennies % 10;
    nickels = pennies / 5;
    pennies = pennies % 5;




    //Displaying a message to the user with desired output

    cout << "Change Due:\n\n";
    cout << dollars << " dollars\n";
    cout << quarters << " quarters\n";
    cout << dimes << " dimes\n";
    cout << nickels << " nickels\n";
    cout << pennies << " pennies\n";


    return 0;

}

【问题讨论】:

  • 只需打印出每一行代码之后的值,看看哪里出错了。调试自己的代码,不要转给别人。
  • 我试了很多次,我就是不明白为什么它给出了错误的输出。
  • 20.14 与大多数有限小数一样,不能在float 中精确表示。实际的表示是一些稍微大一点或小一点的数字。看起来你很不走运,而且它更小 - 比如20.13999999。你将它乘以 100 并截断,最后得到2013 便士。试试pennies = dollarAmount * 100.0 + 0.5; - 这个回合,而不是截断。
  • 成功了,谢谢:)

标签: c++


【解决方案1】:

您必须使用 &lt;cmath&gt; 中包含的 std::fmod 来计算浮点除法的浮点余数。

【讨论】:

    猜你喜欢
    • 2018-12-06
    • 2018-12-12
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 2022-12-16
    相关资源
    最近更新 更多