这段简单的代码有什么问题?

时间:2019-09-15 22:42:57

标签: c++ visual-c++

当执行第一步将输入的四分之一数乘以0.25时,该代码似乎可以正常工作,但随后的两个步骤均无效。

#include <iostream>
using namespace std;

int main()
{
    int quarter, dime, nickle;
    int result;

    quarter = 25;
    dime = 10;
    nickle = 5;

    int numQuarters, numDimes, numNickles;

    cout << "Please enter the number of quarters and press Enter: ";
    cin >> numQuarters;

    cout << "Please enter the number of dimes and press Enter: ";
    cin >> numDimes;

    cout << "Please enter the number of nickles and press Enter: ";
    cin >> numNickles;

    result = (numQuarters * quarter) + (numNickles * nickle) + (numDimes * dime);

    cout << "The total amount of pennies is: " << result;

    return 0;
}

我希望4个季度,10个角钱和20个镍币的产量为300便士

输出为102

编辑:代码已修复,现在可以使用!

1 个答案:

答案 0 :(得分:0)

嗯...您的代码看起来不错,但是我认为您的数学运算顺序有些问题。我只是将nickel的值更改为0.05,将dime的值更改为0.10(我认为这是您的代码中的错误)。我也将*100下移到cout语句,这有助于清除问题...

#include <iostream>
using namespace std;

int main()
{
    float quarter, dime, nickle, penny;
    float result;

    quarter = 0.25;
    dime = 0.10;
    nickle = 0.05;

    float numQuarters, numDimes, numNickles;

    cout << "Please enter the number of quarters and press Enter: "; 
    cin >> numQuarters;

    cout << "Please enter the number of nickles and press Enter: ";
    cin >> numNickles;

    cout << "Please enter the number of dimes and press Enter: ";
    cin >> numDimes;

    result = (numQuarters * quarter) + (numNickles * nickle)+ (numDimes * dime);

    cout << "The total amount of pennies is: " << result * 100;

    return 0;
}

哦,就像@Pete Becker所说的那样,您的计算以美分(整数)为单位。它不仅可以解决浮点数作为金钱的一些小错误,还可以使您的代码更易于阅读和操纵。