Chu279 2021-05-07 23:11 采纳率: 10%

# 求c语言题目！！ 谢谢！ 由计算机随机产生10个0~100之间的整数存入数组a中，并将这些数从小到大

• 写回答

#### 1条回答默认 最新

• benbenli 2021-05-08 00:17
关注

下面是我些的代码和运行结果：

``````// 由计算机随机产生10个0~100之间的整数存入数组a中，并将这些数从小到大排序，然后输入一个整数x，在数组a中查找x，若找到则输出相应的下标，否则输出“未找到”。
#include <stdlib.h>
#include <stdio.h>

#define MAX 100
#define N 10

int a[N];
int count = N;

void populate()
{
for (int i = 0; i < count; ++i)
{
a[i] = rand() % (MAX + 1);
}
}

// 具体要求： (1）用选择排序法或冒泡排序法进行排序。
void bubble_sort()
{
for (int i = 0; i < count - 1; ++i)
for (int j = i + 1; j < count; ++j)
if (a[i] > a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}

// (2)用顺序查找法或折半查找法进行查找。
int find(int x)
{
for (int i = 0; i < count; ++i)
if (a[i] == x)
return i;

return -1;
}

// (3)如果要删除查找到的元素值，如何修改程序?
int remove(int x)
{
for (int i = 0; i < count; ++i)
if (a[i] == x)
{
for (int j = i + 1; j < count; ++j)
a[j - 1] = a[j];
--count;
return i;
}

return -1;
}

// 主函数一次调用前面的函数
int main()
{
int x;
int index;

populate();
bubble_sort();

printf("Here are the %d numbers:\n", count);
for (int i = 0; i < count; ++i)
printf("%d ", a[i]);
printf("\n");

printf("Please enter a number (0 .. 100) to look for and press ENTER: ");
scanf("%d", &x);
index = find(x);
if (index != -1)
printf("Found it! Its index (0-based) is %d\n", index);
else

printf("Please enter a number (0 .. 100) to look for and press ENTER: ");
scanf("%d", &x);
index = find(x);
if (index != -1)
printf("Found it! Its index (0-based) is %d\n", index);
else

printf("Please enter a number (0 .. 100) to delete and press ENTER: ");
scanf("%d", &x);
index = remove(x);
if (index != -1)
printf("Deleted it! Its index (0-based) was %d\n", index);
else

printf("Here are the %d numbers:\n", count);
for (int i = 0; i < count; ++i)
printf("%d ", a[i]);
printf("\n");
}

// Output:
Here are the 10 numbers:
8 12 30 32 32 44 52 54 56 94
Please enter a number (0 .. 100) to look for and press ENTER: 44
Found it! Its index (0-based) is 5
Please enter a number (0 .. 100) to look for and press ENTER: 40
Please enter a number (0 .. 100) to delete and press ENTER: 12
Deleted it! Its index (0-based) was 1
Here are the 9 numbers:
8 30 32 32 44 52 54 56 94     ``````

附注：求赞助积分和C币。加入CSDN将近20年了。最近几年忙小孩没登录。刚才搜索到一本电子书想下载，需要20积分/C币。赞助多少都可以。多谢。

本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥15 c++静态函数的静态函数参数问题
• ¥15 51单片机数码管显示有问题
• ¥30 delphi 10 seattle 调https
• ¥200 有哪位师傅可以教我做出telegraf平台的骰子插件？重酬。
• ¥85 3559A sensor时间同步
• ¥15 IGH主站与elmo驱动器连接时，pdo映射后无法输入输出
• ¥100 Android应用如何动态绑定邀请码
• ¥15 grbl用"!"命令停止移动后，怎么重置？
• ¥15 自己配的nginx 正向代理一直失败（相关搜索：谷歌浏览器|拒绝连接）