You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将main函数中的代码逻辑迁移至自定义函数并在main中调用?

实现方法

核心逻辑是统计两个等长数组中对应位置元素的不匹配数量,我们可以把这部分逻辑封装成独立函数,具体步骤如下:

1. 定义自定义统计函数

函数接收两个待比较的数组(用int*类型接收)、数组长度作为参数,返回不匹配元素的计数:

// 计算两个码字的不匹配数量
int countMismatches(int *codeword1, int *codeword2, int num) {
    int counter = 0;
    for(int i = 0; i < num; i++) {
        if(codeword1[i] != codeword2[i]) {
            counter++;
        }
    }
    return counter;
}

2. 修改main函数调用自定义函数

把原代码中统计不匹配数的循环替换成函数调用,简化main逻辑:

修改后的完整代码

#include <stdio.h>

// 自定义函数:计算两个码字的不匹配数量
int countMismatches(int *codeword1, int *codeword2, int num) {
    int counter = 0;
    for(int i = 0; i < num; i++) {
        if(codeword1[i] != codeword2[i]) {
            counter++;
        }
    }
    return counter;
}

int main()
{
    int num;
    printf("请输入码字的长度:");
    scanf("%d", &num);
    
    // 定义变长数组存储两个码字(C99及以上标准支持)
    int codeword1[num], codeword2[num];
    
    printf("请输入第一个码字:\n");
    for(int i = 0; i < num; i++) {
        scanf("%d", &codeword1[i]);
    }
    
    printf("请输入第二个码字:\n");
    for(int i = 0; i < num; i++) {
        scanf("%d", &codeword2[i]);
    }
    
    // 调用自定义函数获取不匹配数量
    int mismatchCount = countMismatches(codeword1, codeword2, num);
    
    printf("\n\n码字的不匹配数量为:%d\n", mismatchCount);
    
    return 0;
}

优化说明

  • 原代码中的else continue可以直接省略,循环会自动进入下一次迭代,不影响逻辑且简化代码。
  • 原输出部分的if(counter>0)判断多余,直接输出计数即可,无匹配时计数本身就是0。
  • 若编译器不支持变长数组(C99以下标准),可以改用malloc/free动态分配内存创建数组。

内容的提问来源于stack exchange,提问作者Vaibav Reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 00:46:09