C语言递归与排序算法实现

C语言递归与排序算法详解

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, &times);

    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;
}

236、编

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值