以下是我的代码:
#include <stdio.h>
void arrays()
{
int i,n,j;
printf("Enter the size of the arrays:\n");
scanf("%d",&n);
int a1[n];
int a2[n];
int intersection[2*n], unions[n];
printf("Enter elements of the first array:\n");
for (i = 0; i < n; i++)
{
scanf("%d",&a1[i]);
}
printf("Enter elements of the second array:\n");
for (j = 0; j < n; j++)
{
scanf("%d",&a2[j]);
}
int indexs = -1, indexu = -1;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
unions[++indexu] = a1[j];
}
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if(a1[i] == a2[j])
{
intersection[++indexs] = a2[j];
}
else
{
unions[++indexu] = a2[j];
}
}
}
printf("Intersection:\n");
printf("Union:\n");
for(i = 0; i < indexs; i++)
printf("%d",intersection[i]);
for (j = 0; j < indexu; j++)
printf("%d" ,unions[j]);
}现在,我很难找到联合和十字路口。我试图修复我的循环,但我找不到问题在哪里,我正在做的方法是首先比较第一个数组和第二个数组。因为union意味着两个数组中的所有元素。然后,第二个是找到重复的数字将首先到交汇处。或者如果没有存储在联合中的元素。它也将进入联合数组。有人能帮忙吗?谢谢
发布于 2013-09-24 23:29:46
问题之一是输出部分。
printf("Intersection:\n");
printf("Union:\n");
for(i = 0; i < indexs; i++)
printf("%d",intersection[i]);
for (j = 0; j < indexu; j++)
printf("%d" ,unions[j]);此代码段在打印数组内容之前打印出"Intersection:\n"和"Union:\n"。这就是为什么你认为它不会出现交叉点。
正确的代码应该是:
printf("Intersection:\n");
for(i = 0; i <= indexs; i++)
printf("%d",intersection[i]);
printf("\n");
printf("Union:\n");
for (j = 0; j <= indexu; j++)
printf("%d" ,unions[j]);
printf("\n");https://stackoverflow.com/questions/18993708
复制相似问题