#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 \n",&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 \n",&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;
}
}
}
}
这是我的程序
我希望它能给出数组中的公共元素,但它没有占用我想要的元素数量 如果我想在数组中输入 4 个元素,它需要超过 4
在测试代码时,主要问题在于“scanf”函数调用中使用的格式。例如,以下 scanf 调用因格式中包含换行符而变得混乱。
scanf("%d \n",&a[i]);
仔细阅读了您的代码,以下是一个重构版本,对 scanf 函数进行了一些清理,并添加了一些额外的输出文本,使程序更加用户友好。
#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++)
{
printf("Element: "); /* To provide some user friendly prompting */
scanf("%d", &a[i]); /* Clean up of the scanf formatting */
}
printf("Enter n.o of ele to enter in B \n");
scanf("%d",&m); /* Clean up of the scanf formatting */
printf("Enter elements into array B:\n");
for(j=0; j<m; j++)
{
printf("Element: "); /* To provide some user friendly prompting */
scanf("%d", &b[j]); /* Clean up of the scanf formatting */
}
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; /* Should not want this if all matches are to be printed */
}
}
}
return 0;
}
请注意,换行符和空格填充等项目已被删除。通过这些重构,下面是对重构代码的测试。
@Vera:~/C_Programs/Console/Intersect/bin/Release$ ./Intersect
enter n.o of ele to enter in A
3
enter elements into array A:
Element: 44
Element: 88
Element: 77
Enter n.o of ele to enter in B
3
Enter elements into array B:
Element: 77
Element: 55
Element: 88
Common ele are :
88
77
你可能想对 scanf 函数做更多的研究,但试试这个重构代码,看看它是否符合你项目的精神。