有人可以在这段代码中找到错误吗?

时间:2017-09-10 01:46:49

标签: c++

我编写了这个程序,当我运行它并输入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;

}

1 个答案:

答案 0 :(得分:0)

您必须使用std::fmod中包含的<cmath>来计算浮点除法的浮点余数。