二、编写程序把长度为10的数组中所有奇数和偶数分别存放在另外两个数组中并输出
时间: 2023-03-27 16:03:00 浏览: 78
好的,我可以回答这个问题。以下是程序的代码:
#include <stdio.h>
int main() {
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int odd[10], even[10];
int odd_count = , even_count = ;
for (int i = ; i < 10; i++) {
if (arr[i] % 2 == ) {
even[even_count] = arr[i];
even_count++;
} else {
odd[odd_count] = arr[i];
odd_count++;
}
}
printf("奇数数组:");
for (int i = ; i < odd_count; i++) {
printf("%d ", odd[i]);
}
printf("\n");
printf("偶数数组:");
for (int i = ; i < even_count; i++) {
printf("%d ", even[i]);
}
printf("\n");
return ;
}
相关问题
编写程序,用数组分别建两个堆栈共享,输入一序列整数,将奇数和偶数分别存放在两个栈中,栈满后打印
下面是使用C++语言编写的程序:
```cpp
#include <iostream>
#define MAXSIZE 10
using namespace std;
class Stack {
private:
int top1, top2;
int data[MAXSIZE];
public:
Stack() {
top1 = -1;
top2 = MAXSIZE;
}
bool isFull() {
return top1 + 1 == top2;
}
bool isEmpty(int stackNum) {
if (stackNum == 1) {
return top1 == -1;
} else {
return top2 == MAXSIZE;
}
}
void push(int stackNum, int value) {
if (isFull()) {
cout << "Stack is full!" << endl;
return;
}
if (stackNum == 1) {
top1++;
data[top1] = value;
} else {
top2--;
data[top2] = value;
}
}
int pop(int stackNum) {
if (isEmpty(stackNum)) {
cout << "Stack is empty!" << endl;
return -1;
}
if (stackNum == 1) {
int value = data[top1];
top1--;
return value;
} else {
int value = data[top2];
top2++;
return value;
}
}
};
int main() {
Stack s;
int n, x;
cout << "Enter the number of integers: ";
cin >> n;
cout << "Enter the integers:" << endl;
for (int i = 0; i < n; i++) {
cin >> x;
if (x % 2 == 0) {
s.push(1, x);
} else {
s.push(2, x);
}
}
cout << "Even numbers: ";
while (!s.isEmpty(1)) {
cout << s.pop(1) << " ";
}
cout << endl;
cout << "Odd numbers: ";
while (!s.isEmpty(2)) {
cout << s.pop(2) << " ";
}
cout << endl;
return 0;
}
```
程序中使用了一个名为 `Stack` 的类来表示共享堆栈,它包含两个栈指针 `top1` 和 `top2`,表示两个栈的栈顶元素位置,以及一个数组 `data`,用来存储栈中的元素。
类中提供了一些方法,比如 `isFull` 用来判断堆栈是否满了,`isEmpty` 用来判断某个栈是否为空,`push` 用来将元素压入堆栈,`pop` 用来从堆栈中弹出元素。
在主函数中,先输入整数序列,并将奇数和偶数分别压入两个栈中,最后依次输出两个栈中的元素。
.编写函数把数组中所有的奇数放在一个数组 中,并在主函数中输出。
好的,以下是一个实现该功能的 C++ 函数的代码:
```cpp
#include <iostream>
#include <vector>
// 将数组中所有的奇数放在一个数组中
std::vector<int> odd_numbers(int arr[], int size)
{
std::vector<int> odds;
for (int i = 0; i < size; i++) {
if (arr[i] % 2 != 0) {
odds.push_back(arr[i]);
}
}
return odds;
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int size = sizeof(arr) / sizeof(int);
std::vector<int> odds = odd_numbers(arr, size);
std::cout << "Odd numbers: ";
for (int i = 0; i < odds.size(); i++) {
std::cout << odds[i] << " ";
}
std::cout << std::endl;
return 0;
}
```
这个函数接收一个整型数组和它的大小作为参数,然后遍历数组,将所有的奇数放入一个 `std::vector<int>` 中,并返回该向量。在主函数中,我们调用该函数并输出结果。