从一系列的evens和赔率中,新数组是持续的第一个赔率
From array of evens and odds make new array where evens first odds last
好吧,所以当我打印最终数组(arr2)时,第一个从奇数[]到arr2 []的元素是一个随机数,而不是奇数插入ARR1 []的数字。这是图片作为示例图片。
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
int arr[20], odd[20],arr2[20], i, j = 0, k = 0, no,temp,temp2,o=1;
cout << "Size of Array: ";
cin >> no;
cout << "Enter any " << no << " elements in Array: ";
for (i = 0; i<no;i++)
{
cin >> arr[i];
}
for (i = 0; i<no;i++)
{
if (arr[i] % 2 == 0)
{
arr2[j] = arr[i];
j++;
temp = j+1;
}
else
{
odd[k] = arr[i];
k++;
temp2 = k;
}
}
cout << endl;
cout << "New array:" << endl;
for (i = 1; i <= temp2; i++)
{
arr2[temp] = odd[o];
temp++;
o++;
}
for (i = 0;i < no;i++)
{
cout << arr2[i] <<endl;
}
}
我还没有看到您的问题的来源。但是,有一种使用std::sort
进行此操作的方法。这是我的方式:
#include <iostream>
#include <algorithm>
using namespace std;
bool sortingFunction(int left, int right)
{
if (left % 2 == 0 && right % 2 == 0 || left % 2 != 0 && right % 2 != 0)
return left<right;
else if (left % 2 != 0 && right % 2 == 0)
return false;
else if (left % 2 == 0 && right % 2 != 0)
return true;
}
int main()
{
int no;
cout << "Size of Array: ";
cin >> no;
int arr[no];
cout << "Enter any " << no << " elements in Array: ";
for (int i = 0; i<no;i++)
{
cin >> arr[i];
}
std::sort(arr,arr+no,sortingFunction);
for (int i = 0; i< no; i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}
有两个错误
而不是temp = j 1,您应该写temp =j。
在添加arr2中的值后,
j在所有数字后都指向索引。
第二个是在第三循环中使用o作为索引,但使用1初始化,应使用0。
初始化。您的代码应该像
void main()
{
int arr[20], odd[20], arr2[20], i, j = 0, k = 0, no, temp, temp2, o = 0;
cout << "Size of Array: ";
cin >> no;
cout << "Enter any " << no << " elements in Array: ";
for (i = 0; i<no; i++)
{
cin >> arr[i];
}
for (i = 0; i<no; i++)
{
if (arr[i] % 2 == 0)
{
arr2[j] = arr[i];
j++;
temp = j;// +1;
}
else
{
odd[k] = arr[i];
k++;
temp2 = k;
}
}
cout << endl;
cout << "New array:" << endl;
for (i = 1; i <= temp2; i++)
{
arr2[temp] = odd[o];
temp++;
o++;
}
for (i = 0; i < no; i++)
{
cout << arr2[i] << endl;
}
cin >> arr2[0];
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '