求和查找器不一致

Sum finder not consistent

本文关键字:不一致 查找 求和      更新时间:2023-10-16

这里的代码查找小于或等于某个数字的某些给定倍数的和。它使用了我不久前在网上读到的一个公式的修改版本(这个公式是用来求所有小于或等于100或1000的数字的和——当我在基督教青年会等人来接我的时候写的,所以它可能看起来不像网上的那个公式)。我用的是(n+x)(n/x/2)这里n是极限(比如1000)x是倍数(比如1 3 5)所以如果n = 1000 x = 5,它应该求出小于等于1000的所有5的倍数的和。有时是正确的,有时不是。例如,如果我选择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
    andn5 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 thenmultiples 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));
    }

变化

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。