我想编写这个程序来从用户那里读取元素的数量和一个列表,打印两个数组,一个用于偶数,一个用于奇数,并显示第一个数组中零的数量。
我纠正了错误,现在没有错误但输出错误。这是代码:
#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