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

C语言求两数组交集程序:输入元素数量不符问题排查

问题原因与修复方案

核心问题

  1. 头文件语法错误:#include <stdio.h>;末尾多了分号,这会触发编译错误,必须删掉。
  2. scanf格式串的空格陷阱:所有scanf里%d后面的空格是关键问题。比如scanf("%d ", &a[i]);,scanf会在读取完整数后,持续跳过所有空白字符(空格、换行、制表符),直到碰到非空白字符才会返回。这就导致你输入指定数量的元素后,程序还会一直等待输入,必须再输入一个非空白内容才会结束输入循环。
  3. 换行符使用错误:代码里的 是无效的换行写法,应该用标准的\n来实现换行,否则输出排版会混乱。

修正后的代码

#include <stdio.h>

int main() {
    int a[100], b[100], n, m, i, j;
    printf("enter n.o of ele to enter in A\n");
    scanf("%d", &n);
    printf("enter elements into array A:\n");
    for (i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }
    printf("enter n.o of ele to enter in B\n");
    scanf("%d", &m);
    printf("enter elements into array B:\n");
    for (j = 0; j < m; j++) {
        scanf("%d", &b[j]);
    }
    printf("common ele are :\n");
    for (i = 0; i < n; i++) {
        for (j = 0; j < m; j++) {
            if (a[i] == b[j]) {
                printf("%d\n", a[i]);
                break;
            }
        }
    }
    return 0; // 补充main函数标准返回值,符合C语言规范
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:52:11