このプログラムを作成して、ユーザーから要素の数とリストを読み取り、偶数と奇数の 2 つの配列を出力し、最初の配列のゼロの数を表示したいと考えています。
エラーを修正しました。エラーはなくなりましたが、出力が間違っています。コードは次のとおりです。
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
// Function prototypes
int count(const int list[], int size, int & odd_num, int & even_num);
void split(const int list[], int size, int list_even[], int even_num, int list_odd[], int odd_num );
void print_list(int array[], int length);
int main()
{
int size; // llength of the array, user input
int zero_num; // number of zeros
int even_num;
int odd_num;
int * list; // array to store the user inputs
// Prompt and read number of elements from the user into the variable size
cout << "Enter number of elements: ";
cin >> size;
// Create a new array of size length and assign it to variable list
list = new int [size];
// Prompt and read the elements from the user
cout << "Enter list: "<<endl;
for (int i=0; i<size; i++)
{
cin>> list[i];
}
// Call function count and save its return value in variable num_zero
zero_num = count(list,size,odd_num,even_num);
// allocate an array for even numbers
int * list_even;
list_even = new int [even_num];
// allocate an array for odd numbers
int * list_odd;
list_odd= new int [odd_num];
//
split(list, size, list_even, even_num, list_odd, odd_num);
cout << "Even elements: ";
print_list(list_even, even_num);
cout<< endl;
cout << "Odd elements: ";
print_list(list_odd, odd_num);
cout << endl;
// Delete the lists
delete[]list;
delete[]list_even;
delete[]list_odd;
return 0;
}
//functions
//function to count the odd and even numbers and th enumber od zeros
int count(const int list[], int size, int & odd_num, int & even_num)
{
int i(0); //while loop variable
int even(0); // variable to count even numbers
int odd (0); // variable to count odd numbers
int zero(0); // variable to count zeros
while (i<size)
{
if (list[i] == 0)
{
zero++;
}
else if (list[i]% 2 ==0)
{
even++;
}
else
{
odd++;
}
i++;
}
return zero;
}
// function to copy odd and even number to seperate arrays
void split(const int list[], int size, int list_even[], int even_num, int list_odd[], int odd_num )
{
int j(0);
int k(0);
while (j<even_num && k<odd_num)
{
for (int i(0); i<size; i++)
{
if(list[i]%2 == 0)
{
list_even[j]= list[i];
j++;
}
if(list[i]%2 == 1)
{
list_odd[k]= list[i];
k++;
}
}
}
}
// function to print an array
void print_list(int array[], int length)
{
cout << array << endl;
}
入力と出力の例を次に示します。
Enter number of elements: 6
Enter list:
1
2
3
4
5
6
Even elements: 0x988030
Odd elements: 0x7f601e480010