好的,所以当我打印最后一个数组(arr2)时,从odd []复制到arr2 []的第一个元素是一个随机数,而不是它是插入arr1 []中的奇数。这是一张图片pic。
#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;
}
}
答案 0 :(得分:0)
我还没有看到你的问题来自哪里。但是,使用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;
}
答案 1 :(得分:0)
有两个错误
而不是temp = j + 1,你应该写temp = j。
当你在arr2中添加值后增加j时,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];
}