c++ - 在函数中使用 fmod,循环逻辑返回意外值

标签 c++

我正在编写一个程序,它计算元素的成本和支付的金额,并计算您应该找回每枚硬币的多少(四分之一、一角、五分、一分)。在计算还需要多少个季度的函数中,它总是返回 2

float calculateCoins(float change)

{
    int x=1;
    float result=1;

    while (result>0)
    {
        result =fmod(change, (.25 * x));
        x++;
    }

    return x;

我不确定哪里出了问题。

另外,请原谅我低效的代码,可能还有丑陋的代码,我还在学习

#include <iostream>
#include <math.h>
using namespace std;

float calculateChange(float, float);
float calculateCoins(float);

int main()
{
    float amountPay, amountDue, changeDue, quarter;

    cout << "This program calculates how much change should be returned "
         << "\nwhen a payment is made" << endl << endl;
    cout << "Please input the cost of the item:" << endl;
    cin >> amountDue;
    cout << endl << "Please input the amount paid:" << endl;
    cin >> amountPay;

    changeDue = calculateChange(amountDue,amountPay);
    quarter = calculateCoins(changeDue);

    cout << changeDue << endl;
    cout << quarter << " quarters needed";
    return 0;
}

float calculateChange(float amount, float payment)
{
    return payment-amount;
}
float calculateCoins(float change)
{
    int x=1;
    float result=1;

    while (result>0)
    {
        result =fmod(change, (.25 * x));
        x++;
    }

    return x;


}

最佳答案

您的问题是,函数 calculateCoins(float change) 背后的逻辑是错误的。

您首先使用值 1 初始化 result。 在您的循环中,您检查 result > 0

在您的第一次迭代中,这将始终为真,因为您已使用 1 初始化了 result。在循环体中,将 result 的值更改为模数,并增加 x 的值,现在为 2。只有当模数发生变化时,循环才会停止x 为 0。这显然不是您所期望的。

试试这个: 成本 = 1.1 付费 = 2 你最终会陷入无限循环。

以此为起点:

float calculateCoins(float change)
{
    int x=1;
    float result=1;

    while (change - x*0.25 > 0)
    {
        x++;
    }

    return x;
}

我不确定您的预期结果是什么。 试着弄清楚如果你输入奇怪的数字会发生什么,比如 cost = 1.1 paid = 2

关于c++ - 在函数中使用 fmod,循环逻辑返回意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53485234/

相关文章:

c++ - 使用自定义容器并发 vector 更改 boost 图邻接列表中的容器生成器

C++ 从 std::exception 获取调用堆栈

c++ - 处理其他信号时等待信号

c++ - GLEW 链接错误。错误 LNK2019

c++ - 从大 vector 中删除字符串列表的有效方法

c++ - 更改函数中的全局变量

c++ - 程序正在跳过 getline ()/C++

c++ - 这到底是什么意思(C++ 函数指针)?

c++ - Mac 上的 Qt::Sheet 和 QMessageBox::show()

C++ WinAPI - 草率的鼠标输入