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

C语言数组移位匹配程序输出false错误排查与修复

代码错误分析与修正方案

存在的错误点

  • 数组输入逻辑错误:输入元素时你错误使用数组长度n作为下标,所有输入值都被写到了first_array[n]、second_array[n]的位置,数组前n个有效位置存储的都是未初始化的垃圾值,后续操作完全无效。
  • 数组对比逻辑错误:C语言中数组名代表数组首地址,直接用==对比两个数组,实际是对比两个数组的内存地址是否相同,和数组元素没有任何关系,所以这个判断永远为假。
  • 冗余无用代码:#define input、#define N 5两个宏定义没有任何作用,属于冗余代码。

修正后的完整代码

#include<stdio.h>

// 移位函数:将数组首元素移到末尾
void shift(int a[], int n) {
    int i;
    int first_element = a[0];
    for(i=1; i<n; i++) {
        a[i-1] = a[i];
    }
    a[n-1] = first_element;
}

// 辅助函数:判断两个等长数组元素是否完全相等
int array_equal(int a[], int b[], int n) {
    for(int i=0; i<n; i++) {
        if(a[i] != b[i]) {
            return 0;
        }
    }
    return 1;
}

int main() {
    int i, n;
    int shift_counter = 0;
    int first_array[100];
    int second_array[100];
    printf("Enter the length of the input array: ");
    scanf("%d", &n);

    printf("Enter the elements of the first array: ");
    for(i=0; i<n; i++) {
        // 修正下标为循环变量i
        scanf("%d", &first_array[i]);
    }

    printf("Enter the elements of the second array: ");
    for(i=0; i<n; i++) {
        // 修正下标为循环变量i
        scanf("%d", &second_array[i]);
    }

    // 最多移位n次就会回到原数组,不需要额外判断
    while (shift_counter < n) {
        // 调用辅助函数对比数组元素
        if (array_equal(first_array, second_array, n)) {
            printf("Output: true");
            return 0;
        }
        shift(first_array, n);
        shift_counter++;
    }
    // 移位n次都不匹配则输出false
    printf("Output: false");
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:18:00