求和器不一致

时间:2015-07-23 00:57:05

标签: c++ sum

我的代码在这里找到一些给定倍数的总和小于或等于某个数字。它使用了我之前在互联网上阅读的公式的修改版本(用于查找所有数字的总和小于或等于100,或1000或者其他 - 当我在等待时编写公式时在ymca接听,因此它可能看起来不像来自互联网的那个)。所以对我来说,我使用了(n + x)(n / x / 2),其中n是极限(例如1000),x是你正在使用的倍数(所以1,或3或5)。因此,如果n = 1000且x = 5,则应找到5的所有倍数之和小于或等于1000)。 有时它会正确加起来,有时却不会。 例如,如果我选择1和2作为倍数,20作为限制,则打印出320(如果添加1 + 2 + 3 ... + 20然后添加到2 + 4 + 6,这是正确的... + 20)。 但是,如果我将3和5和1000的倍数作为限制,则打印出266,998(根据互联网这是错误的)。 我不明白为什么它在第一次运作而不是第二次运作(我只用了1年的高中数学,我将是一名大二学生)。 这是代码:

/*
Finds the sum of all inputted multiples below a certain number
For example, it could find the sum of all the multiples of 3 and 5 less than
or equal to 1000
Written By Jay Schauer
*/

//Data Declarations
#include <iostream>

int main()
{
    using namespace std;

    int a; //Stores the number of multiples being used

    cout << "Enter the amount of multiples you would like to use (up to 50
    << endl;

    cout << "(for example, enter '2' if you would like to use two multiples,
    maybe 3 and 5?)" << endl;
    cin >> a;

    cout << "Next, you will enter the mutliples you want to use." << endl;

    cout << "(for example, if you want to find the sum of the multiples of 3
    and\n5 below a given amount, enter 3 as 'multiple 1' and 5 as 'multiple
    2')" << endl;

    int multiples[50]; //Stores the multiples being used
    for (int i = 0; i < a; i++)
    {
        cout << "Enter 'multiple " << (i + 1) << "'" << endl;
        cin >> multiples[i];
    }
    int limit; //Stores the limit
    cout << "Enter the the limit for how high you want to add the multiples
    << endl;

    cout << "(for example, you could set the limit to 1000 to find the sum
    of the\nmultiples of 3 and 5 (if you entered those) less than and or
    equal to 1000)" << endl;

    cin >> limit;

    int sum(0); //Stores the sum
    for (int i = 0; i < a; i++)
    {
        sum += ((limit + multiples[i]) * (limit / multiples[i] / 2));
    }
    cout << "The sum is "<< sum << endl;

    system("pause");
    return 0;
}

编辑:我认为问题可能在于公式中没有的代码,因为在3的倍数下使用21作为限制会导致它打印72,而不是84。我仍然不确定编码错误。

编辑2:我将for循环更改为此,所以当限制不是多个

的倍数时,希望它会起作用
for (int i = 0; i < a; i++)
    {
        int max = limit; /*This is done so I can change max in case it isn't
        a multiple of the multiple*/
        while (max % multiples[i] != 0) max--;
        sum += ((max + multiples[i]) * (max / multiples[i] / 2));
    }

1 个答案:

答案 0 :(得分:2)

更改

sum += ((limit + multiples[i]) * (limit / multiples[i] / 2));

sum += (limit + multiples[i]) * (limit / multiples[i]) / 2;

实际上,对于你的3和21的例子,你是计算(24 *(7/2))= 24 * 3 = 72(7乘2的整数除数给出3,剩余部分丢失) ,但你想要计算(24 * 7)/ 2 = 84。