我需要帮助更改计算器的数学方法

时间:2019-03-02 22:55:23

标签: c++

这是我的代码:

#include <iostream>
#include <cmath>
using namespace std;

int GetQuarters(int cents)
{
    int remainder = cents / 25;
    int quarters = cents - remainder / 25;
    return quarters;
}

int GetDimes(int cents)
{
    int dimes = cents / 10;
    return dimes;
}

int GetNickels(int cents)
{
    int nickels = cents / 5;
    return nickels;
}

int GetPennies(int cents)
{
    return 0;
}

int main()
{
    int cents;
    cout << "How much change do you need? " << endl;
    cin >> cents;

    int quarters = 0, nickels = 0, dimes = 0, pennies = 0;

    quarters = GetQuarters(cents);
    cents = quarters * 25;
    nickels = GetNickels(cents);
    nickels = cents / 5;
    dimes = cents / 10;
    dimes = GetDimes(cents);
    pennies = GetPennies(cents);
    pennies = cents;


    cout << "Quarters: " << quarters << endl;
    cout << "Dimes:    " << dimes    << endl;
    cout << "Nickels:  " << nickels  << endl;
    cout << "Pennies:  " << quarters << endl;

    return 0;
}

问题包括:

-四分之一的值与几分钱相同

-Dime值乘以2.5,而不是除以10

-镍值乘以5而不是除以5

其他信息:

-该代码专为0-99值

2 个答案:

答案 0 :(得分:1)

在我看来,这就像一个作业问题,有故意和各种错误 主要功能以错误的顺序执行操作,数学运算符和变量被切换。

尽管如此,本着回答您的问题的精神,您想要的是以下形式:

#include <iostream>
#include <cmath>
using namespace std;

int GetCoins(int& centsByRef, int denomination)
{
    int coins = centsByRef / denomination;
    centsByRef -= coins * denomination;
    return coins;
}

int main()
{
    int cents;
    cout << "How much change do you need? " << endl;
    cin >> cents;

    cout << "Quarters: " << GetCoins(cents, 25) << endl;
    cout << "Dimes:    " << GetCoins(cents, 10) << endl;
    cout << "Nickels:  " << GetCoins(cents, 5) << endl;
    cout << "Pennies:  " << GetCoins(cents, 1) << endl;

    return 0;
}

其中整数除法将每种硬币的数量放入剩余的美分中,并从余数中减去硬币的价值。

答案 1 :(得分:0)

您需要跟踪美分,因为在计算每种硬币类型总计之后剩余的美分可用。无需功能。您需要的只是这段代码:

quarters = cents/25;
cents -=  quarters * 25;
dimes = cents/10;
cents -= dimes * 10;
nickels = cents/5;
cents -= nickels * 5;
pennies = cents;