打印两个数组中的数字

时间:2015-04-15 13:28:42

标签: c arrays loops

我是C编程新手。我试图弄清楚如何比较2个数组并打印出两个数字正在重复的数字。 这是我的代码:

const int SIZE = 5;
int firstArray[SIZE];
int secondArray[SIZE];
int i,j;

for(i=0; i<SIZE; ++i) {
    printf("enter a number: ");
    scanf("%d", &firstArray[i]);
}

for(i=0; i<SIZE; ++i) {
    printf("%d, ", firstArray[i]);
}
printf("into array 1\n");
for(j=0; j<SIZE; ++j) {
    printf("enter a number: ");
    scanf("%d", &secondArray[j]);
}

for(j=0; j<SIZE; ++j){
    printf("%d, ", secondArray[j]);
}
printf("into array 2\n");

for (i = 0; i<SIZE; ++i){
    for(j=i+1; j<SIZE; ++j){
        if(firstArray[i] == secondArray[j]){
            printf("%d", firstArray[i]);

    }
}

示例输入:

array 1: 1, 2, 3, 4, 5
array 2: 3, 4, 5, 6, 7

预期产出:

1, 2, 3, 4, 5 into array 1
3, 4, 5, 6, 7 into array 2
3 has been entered in both array
4 has been entered in both array
5 has been entered in both array

我的代码只允许我执行#34;到数组&#34;输出。我如何实现:

3 has been entered in both array
4 has been entered in both array
5 has been entered in both array

3 个答案:

答案 0 :(得分:2)

将最终循环更改为:

for (i = 0; i<SIZE; ++i)
{
    for(j = 0; j<SIZE; ++j)
    {
        if(firstArray[i] == secondArray[j])
            printf("%d has been entered in both array\n", firstArray[i]);

    }
}

注意:如果至少一个阵列中存在4次超过1次,此代码将重复发送消息(例如4 has been entered in both array)。

答案 1 :(得分:1)

for (i = 0; i<SIZE; ++i){
   for(j = 0; j<SIZE; ++j){
     if(firstArray[i] == secondArray[j]){
          printf("%d has been entered in both array\n", firstArray[i]);
     }
   }
}

此处,在您需要的第二个循环中,您需要将j=i+1更改为j=0,因为您需要检查两个数组中的所有值。另外,修改printf语句以匹配您的预期输出。

Ideone链接:http://ideone.com/YthNkx

答案 2 :(得分:1)

试试这最后一部分:

for (i = 0; i<SIZE; ++i){
    for(j=0; j<SIZE; ++j){
        if(firstArray[i] == secondArray[j]){
            printf("%d", firstArray[i]);
        }
    }
}

您必须将第一个数组中的每个数字与第二个数组中的每个数字进行比较。希望它有所帮助!