求和查找器不一致
Sum finder not consistent
这里的代码查找小于或等于某个数字的某些给定倍数的和。它使用了我不久前在网上读到的一个公式的修改版本(这个公式是用来求所有小于或等于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。
相关文章:
- 大于65535的C++数组[size]引发不一致的溢出
- 在 C++(和 C)中进行类型转换时明显不一致
- 填充上编译器生成的复制构造函数之间的不一致
- 犰狳的 print() 方法和 cout 在从 Rcpp 调用时顺序不一致
- CreateDIBSection为同一图像返回不一致的位图位值
- 在 Qml 中从 QSqlTableModel 中删除单行时视图不一致
- 模板参数推导不一致
- 声明中不一致的no是否违反ODR?
- 如何删除分支因子不一致的树,最大为 30,40
- 从 C++ 函数与 Python 函数返回的不一致值用于偏斜正态分布
- 从 C 字符串构造 std::string 与从另一个 std::string 构造 std::string 不一致
- 这种比较是否不一致(或者存在其他问题)?
- 以下可变参数模板行为是否不一致?
- 如何修复我的链表读数不一致的问题?
- 在C++17中,为什么类模板和函数模板的指针类型推导明显不一致
- void 函数中的指针参数返回不一致的值
- 如何查找导致结果不一致的代码
- 求和查找器不一致
- 名称查找歧义不一致
- 类中定义的友元函数模板是否可用于查找?clang++和g++不一致