不正确的双重计算

时间:2017-01-17 23:02:40

标签: c++ floating-point double

我是c ++的新手,对编程比较陌生,所以虽然我似乎无法解决这个问题,但这可能是一个简单的解决方法。我一直在我的桌子上打我的脑袋试图在我的代码中得到双重方程以产生正确的结果。我已经解决了这个问题好几天了,我试图用几种不同的方式输入双方程式,这就是我现有的方法。例如,当我为poundPowderedSugar = (batchesMade / ((double)(11 / 5)));测试3时,对于双batchesMade,我应该得到1.363636的双倍输出,上限输出为2,但是我得到1.04167,上限输出为2。当我把它作为双poundPowderedSugar = (batchesMade / 2.2);时,我得到的输出小于1.谢谢!

以下是我的计划中导致我麻烦的部分:

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

string pluralize(string singular, string plural, int number) {
    if (number == 1) {
        return singular;

    }
    return plural;
}

int main() {
    int peopleServed = 0;
    cout << "How many people do you need to serve? ";
    cin >> peopleServed;
    cout << endl;

    double batchesMade = (((double)(peopleServed)) / 12);

    double flourBag = (batchesMade / ((double)(13 + (1 / 3))));
    double sugarBag = (batchesMade / 10.0);
    double poundOfButter = (batchesMade / ((double)(1 + (1 / 3))));
    double ozSourCream = (batchesMade / 2.0);
    double dozenEggs = (batchesMade / 12.0);
    double poundPowderedSugar = (batchesMade / ((double)(11 / 5)));
    double ozVanilla =  (batchesMade / ((double)(2 + (2 / 3))));

    cout << "You need to make:  " << ceil(batchesMade) << " ";
    cout << pluralize("batch", "batches", batchesMade) << " of cupcakes.";
    cout << endl << endl;

    cout << "Shopping List for \"Best Ever\" Vanilla Cupcakes" << endl;
    cout << "----------------------------------------------" << endl;
    cout << ceil(flourBag) << " " << pluralize("bag", "bags", ceil(flourBag));
    cout << " of flour" << endl << endl;
    cout << ceil(sugarBag) << " " << pluralize("bag", "bags", ceil(sugarBag));
    cout << " of granulated sugar" << endl << endl;
    cout << ceil(poundOfButter) << " " << pluralize("pound", "pounds", ceil(poundOfButter));
    cout << " of butter" << endl << endl;
    cout << ceil(ozSourCream) << " " << pluralize("container", "containers", ceil(ozSourCream));
    cout << " of sour cream" << endl << endl;
    cout << ceil(dozenEggs) << " dozen eggs";
    cout << endl << endl;
    cout << ceil(poundPowderedSugar) << " " << pluralize("bag", "bags", ceil(poundPowderedSugar));
    cout << " of powdered sugar" << endl << endl;
    cout << ceil(ozVanilla) << " " << pluralize("bottle", "bottles", ceil(ozVanilla));
    cout << " of vanilla" << endl << endl;

    return 0;
}

0 个答案:

没有答案