产生50个1到100的随机整数,并将其中的偶数保存到一个数组中,输出数组中所有数据,并求该数组长度,在指定位置处插入一个任意数据,删除数组中值为X的数据
时间: 2024-09-11 10:07:01 浏览: 46
以下是C语言代码实现您的要求:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 50
int main() {
int random_numbers[SIZE];
int even_numbers[SIZE];
int even_count = 0;
int x, position, value;
int i, j;
// Seed the random number generator
srand(time(NULL));
// Generate random numbers and store even numbers
for (i = 0; i < SIZE; i++) {
random_numbers[i] = rand() % 100 + 1;
if (random_numbers[i] % 2 == 0) {
even_numbers[even_count++] = random_numbers[i];
}
}
// Output even numbers
printf("Even numbers: ");
for (i = 0; i < even_count; i++) {
printf("%d ", even_numbers[i]);
}
printf("\n");
// Print the length of the even numbers array
printf("Length of even numbers array: %d\n", even_count);
// Ask user for position and value to insert
printf("Enter position to insert (1 to %d): ", even_count + 1);
scanf("%d", &position);
printf("Enter value to insert: ");
scanf("%d", &value);
// Insert value at the specified position
if (position < 1 || position > even_count + 1) {
printf("Invalid position!\n");
} else {
for (i = even_count; i >= position; i--) {
even_numbers[i] = even_numbers[i - 1];
}
even_numbers[position - 1] = value;
even_count++;
}
// Output the updated array
printf("Array after insertion: ");
for (i = 0; i < even_count; i++) {
printf("%d ", even_numbers[i]);
}
printf("\n");
// Ask user for value X to delete
printf("Enter value to delete: ");
scanf("%d", &x);
// Delete value X from the array
for (i = 0, j = 0; i < even_count; i++) {
if (even_numbers[i] != x) {
even_numbers[j++] = even_numbers[i];
}
}
// Update the even_count after deletion
even_count = j;
// Output the updated array after deletion
printf("Array after deletion: ");
for (i = 0; i < even_count; i++) {
printf("%d ", even_numbers[i]);
}
printf("\n");
return 0;
}
```
这段代码首先生成了50个1到100之间的随机整数,并且检查了哪些是偶数。然后,它将这些偶数保存到`even_numbers`数组中,并输出这个数组以及其长度。接下来,代码要求用户输入一个位置和值来在数组中插入一个新元素。最后,代码要求用户输入一个要删除的值X,并从数组中删除该值。
请确保在实际运行此代码前,您的环境支持标准输入输出,并且您已经正确地链接了C标准库。
阅读全文