求解一道c++编程题

2024-11-03 03:27:58
推荐回答(2个)
回答1:

#include

using namespace std;


int search(int* p1, int n, int* p2);

void print(int* p, int n);

int main()

{

int arr1[10] = {1,2,3,4,5,6,7,8,9,10};

int arr2[] = { 0 };

int count = search(arr1, 10, arr2);


print(arr1, 10);

print(arr2, count);


system("pause");

}


int search(int* p1, int n, int* p2)

{

int result = 0;

for (int i = 0; i < n; i++)

{

if (p1[i] % 2 != 0)

{

p2[result] = p1[i];

result++;

}

}

return result;

}


void print(int* p, int n)

{

for (int i = 0; i < n; i++)

{

cout << p[i];

}

cout << endl;

}

回答2:

#include "stdafx.h"

#include

using namespace std;

int search(int*p1, int n, int *p2);

void print(int *p, int n);

int main()

{

int a[5] = { 2,9,8,5,4 };

int b[5] = { 0 };

int n=search(a, 5, b);

print(b, n);

system("pause");

return 0;

}

int search(int *p1, int n, int *p2)

{

int i, j;

for (i = 0,j = 0; i < n; i++)

if (p1[i] % 2)

{

p2[j] = p1[i];

j++;

}

return j;


}

void print(int *p, int n)

{

for (int i = 0; i < n; i++)

cout << p[i] << " ";

cout << endl;

}