从一系列的evens和赔率中,新数组是持续的第一个赔率

From array of evens and odds make new array where evens first odds last

本文关键字:赔率 数组 第一个 新数组 evens 一系列      更新时间:2023-10-16

好吧,所以当我打印最终数组(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];
}