c++ - 将可被数字整除的数字插入向量中
问题描述
我得到了整数 15、16、17、18、19 和 20。
我应该只将可被 4 整除的数字放入向量中,然后在向量中显示值。
我知道如何使用数组来解决问题,但我猜我不知道如何正确使用推回或向量。
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> arrmain; int i,j;
for (int i = 15; i <=20 ; i++)
{
//checking which numbers are divisible by 4
if (i%4 == 0)
{ //if number is divisible by 4 inserting them into arrmain
arrmain.push_back(i);
//output the elements in the vector
for(j=0; j<=arrmain.size(); j++)
{
cout <<arrmain[i]<< " "<<endl;
}
}
}
return 0;
}
想要的输出:可被 4 整除的数字:16、20
解决方案
代码中的主要问题是(1)在打印向量值时使用错误的变量来索引向量,即使用cout <<arrmain[i]
而不是cout <<arrmain[j]
; (2) 迭代到j <= arrmain.size()
( 而不是)时j < arrmain.size()
超出arrmain[arrmain.size()]
数组边界出界。0..4
5
一个小问题是您在填充数组时一次又一次地打印数组的内容。您可能希望在第一个循环之后打印一次,而不是在其中一次又一次地打印。
int main()
{
vector<int> arrmain;
for (int i = 15; i <=20 ; i++)
{
//checking which numbers are divisible by 4
if (i%4 == 0)
{ //if number is divisible by 4 inserting them into arrmain
arrmain.push_back(i);
}
}
//output the elements in the vector
for(int j=0; j<arrmain.size(); j++)
{
cout <<arrmain[j]<< " "<<endl;
}
return 0;
}
关于注释中提到的基于范围的 for 循环,请注意,您可以使用以下缩写语法迭代向量的元素:
// could also be written as range-based for loop:
for(auto val : arrmain) {
cout << val << " "<<endl;
}
这种语法称为基于范围的 for 循环,例如在 cppreference.com上进行了描述。
推荐阅读
- javascript - 如何创建可拖动的 Web 组件
- java - 将具有相同标签的 xml 结构解组到不同的字段
- c# - 升级到 NetCore 3.1 后找不到版本 (= 2.2.7) 的软件包 Microsoft.NETCore.App.Host.win-x64
- sql - SQL UPDATE ORA-01427: 单行子查询返回多于一行的计算百分比
- python - 目标结构会影响神经网络性能吗?
- json - 为什么我得到“404 not found”响应,而不是 json-object answer?
- c# - 如何计算内存缓存中文件的空间?
- python - PyParsing:如何解析函数调用并将其作为字符串返回
- python - 使用 sklearn 预测类名
- rust - 为什么将枚举变体与其名称和类型匹配不起作用?