1.编写一个程序,输入两个包含5个元素的数组,先将两个数组升序排序,然后将这两个数组合并成一个升序数组.
int arr1[5] = {0}, arr2[5] = {0};
printf("请输入五个数: ");
scanf("%d %d %d %d %d",&arr1[0],&arr1[1],&arr1[2],&arr1[3],&arr1[4]);
printf("请再输入五个数: ");
scanf("%d %d %d %d %d",&arr2[0],&arr2[1],&arr2[2],&arr2[3],&arr2[4]);
int arr3[5] = {0};
for (int i = 0; i < 5 - 1; i++) {
for (int j = 0; j < 5 - 1 - i; j++) {
if (arr1[j] > arr1[j + 1]) {
int temp = arr1[j];
arr1[j] = arr1[j + 1];
arr1[j + 1] = temp;
}
if (arr2[j] > arr2[j + 1]) {
int temp2 = arr2[j];
arr2[j] = arr2[j + 1];
arr2[j + 1] = temp2;
}
}
}
for (int i = 0; i < 5; i++) {
arr3[i] = arr1[i] + arr2[i];
}
for (int i = 0; i < 5 - 1; i++) {
for (int j = 0; j < j - 1 -i; j++) {
if (arr3[j] > arr3[j + 1]) {
int temp = arr3[j];
arr3[j] = arr3[j + 1];
arr3[j + 1] = temp;
}
}
}
for (int i = 0; i < 5; i++) {
printf("%d ",arr3[i]);
}
2.(**)随机产生20个10~50的正整数存放到数组中,并求数组中的所有元素最大值、最小值、平均值及各元素之和.
char arr[20] = {0};
int max = 0, min = 50;
int sum = 0;
for (int i = 0; i < 20; i++) {
arr[i] = arc4random() % (50 - 10 + 1) + 10;
}
for (int i = 0; i < 20; i++) {
max = arr[i] > max ? arr[i] : max;
min = arr[i] < min ? arr[i] : min;
sum += arr[i];
}
printf("最大值为%d,最小值为%d,总和为%d,平均值为%d\n",max,min,sum,sum/20);
3.(**)编写整型数组排序程序(冒泡–降序).
int a[] = {3, -9, 32, 77, 63, -24, 14, 0, 21, 45};
for (int i = 0; i < 10 - 1; i++) {
for (int j = 0; j < 10 - 1 - i; j++) {
if (a[j] < a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int i = 0; i < 10; i++) {
printf("%d ",a[i]);
}
printf("\n");
4.(***)找出下列整型数组中最大和最小值及其所在位置i.
int arr[] = {3, -9, 32, 77, 63, -24, 14, 0, 21, 45};
int max = 0, min = 77;
int maxIndex = 0, minIndex = 0;
for (int i = 0; i < 10; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
for (int i = 0; i < 10; i++) {
if (max == arr[i]) {
maxIndex = i;
}
if (min == arr[i]) {
minIndex = i;
}
}
printf("第%d个数为最大值%d,第%d个数为最小值%d\n",maxIndex,max,minIndex,min);
5.(****)思考题:编程在一个已知的字符串中找最长单词,假定字符串中只含字母和空格,空格用来分隔不同单词。
比如:”ni hao world”,最长单词是world。
char str[] = "I am a wonderful boy";
int maxLength = 0;//最长长度
int currentLength = 0;//当前单词的长度(每个单词长度)
int i = 0;//下标
int index = 0;//最长单词的起始位置
while (str[i] != '\0') {
if (str[i] != ' ') {
currentLength++;
if (str[i+1]=='\0') {
if (maxLength < currentLength) {
maxLength = currentLength;
index = i+1 - maxLength;
}
}
}else {
if (maxLength < currentLength) {
maxLength = currentLength;
index = i - maxLength;
}
currentLength = 0;
}
i++;
}
printf("%d\n",maxLength);
for(int i = index;i < maxLength+index;i++){
printf("%c",str[i]);