我正在尝试计算Vector可以被3或5整除的数量。正确的答案是19,但是我的代码返回18。
有人可以解释我在做什么错,以便我能理解吗?谢谢!
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int count {};
vector<int> vec {1,3,5,15,16,17,18,19,20,21,25,26,27,30,50,55,56,58,100,200,300,400,500,600,700};
for(int i=1; i<=vec[i]; ++i)
{
if(vec[i] % 3 == 0 || vec[i] % 5 == 0)
{
count+=1;
}
}
cout << "Odd Numbers In Vector: " << count << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
pax*_*blo 11
向量与数组一样,从零开始而不是从1 开始索引。另外,我不确定为什么要使用数组中的值来确定终止条件。
我怀疑您的for声明应该是(也使用特定类型):
for (vector<int>::size_type i = 0; i < vec.size(); ++i)
Run Code Online (Sandbox Code Playgroud)
我还想提出两点:
那不是基于范围的for。基于范围的for将类似于for (auto val: vec)。
您的if语句捕获了三到五个的倍数,这些数字与输出语句似乎表明的所有奇数的集合之间存在巨大差异。
这是我使用基于范围的for循环并修改测试以计算奇数和三或五的倍数的方法(只需删除您不感兴趣的一个):
#include <iostream>
#include <vector>
using namespace std;
int main() {
int countOdd {0};
int countMult {0};
vector<int> vec {
1, 3, 5, 15, 16, 17, 18, 19, 20,
21, 25, 26, 27, 30, 50, 55, 56, 58,
100, 200, 300, 400, 500, 600, 700
};
for (const auto val: vec) {
if (val % 2 == 1)
++countOdd;
if (val % 3 == 0 || val % 5 == 0)
++countMult;
}
cout << "Count of odd numbers : " << countOdd << '\n';
cout << "Count of multiples of 3 or 5: " << countMult << '\n';
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |