gpt4 book ai didi

c++ - 求和器不一致

转载 作者:行者123 更新时间:2023-11-28 02:23:11 24 4
gpt4 key购买 nike

我的代码在这里找到一些小于或等于某个数字的给定倍数的总和。它使用了我不久前在互联网上读到的公式的修改版本(用于计算小于或等于 100 或 1000 或其他数字的所有数字之和的公式 - 当我在等待时写我的公式在 ymca 领取,所以它可能看起来不像互联网上的那个)。所以对我来说,我使用了 (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
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));
}

最佳答案

改变

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。

关于c++ - 求和器不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31576483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com