233、考虑一个正整数n并执行以下算法:a. 如果它是偶数,将其除以2(n/2)。b. 如果它是奇数,将其乘以3再加1(3n + 1)。对每个生成的数字重复相同的过程。编写一个递归函数,该函数以一个正整数作为参数,并显示生成的数字序列。
以下是实现该功能的递归函数代码:
#include <stdio.h>
int collatz(int n) {
printf("%d\n", n);
if (n == 1)
return 1;
else if (n & 1) /* 如果n是奇数 */
return collatz(3 * n + 1);
else /* 如果n是偶数 */
return collatz(n / 2);
}
234、编写一个函数,该函数接收三个整数作为参数,检查前两个数的和是否等于第三个数。如果相等,函数应返回前两个数中较大的数;否则,返回第二个数和第三个数中较小的数。编写一个程序,读取三个整数,调用该函数并显示返回值。
以下是实现该功能的 C 语言代码:
#include <stdio.h>
int checkSum(int a, int b, int c) {
if (a + b == c) {
return (a > b) ? a : b;
} else {
return (b < c) ? b : c;
}
}
int main(void) {
int num1, num2, num3;
printf("Enter three integers: ");
scanf("%d%d%d", &num1, &num2, &num3);
int result = checkSum(num1, num2, num3);
printf("The result is: %d\n", result);
return 0;
}
235、编写一个函数,用于在双精度浮点数数组中搜索一个数字。如果该数字存在于数组中,函数应返回其首次出现的位置,同时通过指针参数返回其出现的次数;否则返回 -1。编写一个程序,最多读取 100 个双精度浮点数并存储在数组中。如果用户输入 -1,则停止输入数字。然后,程序应读取一个双精度浮点数,并使用该函数显示该数字在数组中出现的次数以及首次出现的位置。
以下是实现该功能的代码:
#include <stdio.h>
#define SIZE 100
// 线性搜索函数
int linear_search(double arr[], int size, double num, int *t) {
int i, pos;
pos = -1;
*t = 0;
for (i = 0; i < size; i++) {
if (arr[i] == num) {
(*t)++;
if (pos == -1) {
pos = i;
}
}
}
return pos;
}
int main(void) {
int i, times, pos;
double num, arr[SIZE];
for (i = 0; i < SIZE; i++) {
printf("Enter number: ");
scanf("%lf", &num);
if (num == -1) {
break;
}
arr[i] = num;
}
printf("Enter number to search: ");
scanf("%lf", &num);
pos = linear_search(arr, i, num, ×);
if (pos == -1) {
printf("%f isn't found\n", num);
} else {
printf("%f appears %d times (first pos = %d)\n", num, times, pos);
}
return 0;
}
C语言递归与排序算法详解

最低0.47元/天 解锁文章
2548

被折叠的 条评论
为什么被折叠?



