C语言随机产生十个一百以内的数放在一个数组中的代码
时间: 2024-02-20 15:58:08 浏览: 25
下面是一个使用C语言在数组中随机产生十个一百以内的数的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10 // 数组大小为10
int main()
{
int i, num;
int arr[SIZE]; // 定义一个大小为10的数组
srand(time(NULL)); // 使用当前时间作为随机数生成器的种子
for(i = 0; i < SIZE; i++)
{
num = rand() % 100 + 1; // 产生1-100之间的随机数
arr[i] = num; // 将随机数存入数组中
}
printf("随机产生的十个数为:\n");
for(i = 0; i < SIZE; i++)
{
printf("%d ", arr[i]); // 输出数组中的数
}
return 0;
}
```
在这个示例中,使用了一个大小为10的数组来存储随机产生的十个数。在循环中,每次随机产生一个1-100之间的数,并将其存入数组中。最后使用另一个循环输出数组中的数。
相关问题
用C语言编写随机产生10万个10000以内的数插入排序
插入排序是一种简单的排序算法,适用于小规模数据的排序。下面是一个使用C语言编写的随机产生10万个10000以内的数插入排序的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void insertion_sort(int arr[], int n) {
int i, j, key;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main() {
int n = 100000;
int max = 10000;
int arr[n];
// 随机生成n个10000以内的整数
srand((unsigned int)time(NULL));
for (int i = 0; i < n; i++) {
arr[i] = rand() % max + 1;
}
// 使用插入排序排序
insertion_sort(arr, n);
// 输出排序后的数组
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
这段代码将生成包含10万个10000以内整数的数组,然后使用插入排序对数组进行排序,最终输出排序后的数组。由于数组较大,排序可能需要一些时间。
用C语言编写随机产生10万个10000以内的数排序
可以使用C语言中的标准库函数`qsort()`对数组进行排序。下面是一个简单的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 比较函数,用于qsort()排序
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int main() {
int n = 100000;
int max = 10000;
int arr[n];
// 随机生成n个10000以内的整数
srand((unsigned int)time(NULL));
for (int i = 0; i < n; i++) {
arr[i] = rand() % max + 1;
}
// 使用qsort()排序
qsort(arr, n, sizeof(int), compare);
// 输出排序后的数组
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
这段代码将生成包含10万个10000以内整数的数组,然后使用`qsort()`函数对数组进行排序,最终输出排序后的数组。由于数组较大,排序可能需要一些时间。