从用户(L1 和 L2)读取两个数组并在 L2 是 L1 的子数组时打印 L1 - L2 的程序
Program that read two arrays from the user(L1 and L2) and prints L1 - L2 if L2 is a sub array of L1
我创建了这个程序,它从用户(L1 和 L2)读取两个数组,如果 L2 是 L1.For 示例的子数组,则打印 L1 - L2,如果 L1 ={'a', '2','c','d','e'} 和 L2 ={'2','c','d'} 然后
它应该打印 {'a', 'e'}。但是我在输出中遇到了一些问题。我只得到一些值的正确输出,但对于大多数值,我得到的 L2 不是 L1 的子数组。
#include<stdlib.h>
#include<stdio.h>
int main() {
int n1, n2, j = 0, i = 0, temp = 0, a = 0;
//ARRAY INPUT
printf("Enter number of characters in L1: ");
scanf("%d", &n1);
int l1[n1];
for (int i = 0; i < n1; i++) {
printf("Enter character %d: ", i + 1);
scanf(" %c", &l1[i]);
}
printf("Enter number of characters in L2: ");
scanf("%d", &n2);
int l2[n2];
for (int i = 0; i < n2; i++) {
printf("Enter character %d: ",i + 1);
scanf(" %c", &l2[i]);
}
//FOR L1 > L2
while (i < n1) {
if(l1[i] == l2[j]) {
i++;
j++;
if (j == n2) {
a = 1;
break;
}
}
else {
i = temp + 1;
temp = i;
j = 0;
}
}
if (a == 0) {
printf("l2 is not a sub array of l1");
}
else if (a == 1) {
printf("{");
for (int i = 0; i < n1; i++) {
if (i >= temp && i < (temp + n2))
continue;
printf("%c ", l1[i]);
}
printf("}");
}
exit(0);
}```
您的 'Arrays' 应该是 char
数组而不是 int
。
char l1[n1];
char l2[n2];
我创建了这个程序,它从用户(L1 和 L2)读取两个数组,如果 L2 是 L1.For 示例的子数组,则打印 L1 - L2,如果 L1 ={'a', '2','c','d','e'} 和 L2 ={'2','c','d'} 然后 它应该打印 {'a', 'e'}。但是我在输出中遇到了一些问题。我只得到一些值的正确输出,但对于大多数值,我得到的 L2 不是 L1 的子数组。
#include<stdlib.h>
#include<stdio.h>
int main() {
int n1, n2, j = 0, i = 0, temp = 0, a = 0;
//ARRAY INPUT
printf("Enter number of characters in L1: ");
scanf("%d", &n1);
int l1[n1];
for (int i = 0; i < n1; i++) {
printf("Enter character %d: ", i + 1);
scanf(" %c", &l1[i]);
}
printf("Enter number of characters in L2: ");
scanf("%d", &n2);
int l2[n2];
for (int i = 0; i < n2; i++) {
printf("Enter character %d: ",i + 1);
scanf(" %c", &l2[i]);
}
//FOR L1 > L2
while (i < n1) {
if(l1[i] == l2[j]) {
i++;
j++;
if (j == n2) {
a = 1;
break;
}
}
else {
i = temp + 1;
temp = i;
j = 0;
}
}
if (a == 0) {
printf("l2 is not a sub array of l1");
}
else if (a == 1) {
printf("{");
for (int i = 0; i < n1; i++) {
if (i >= temp && i < (temp + n2))
continue;
printf("%c ", l1[i]);
}
printf("}");
}
exit(0);
}```
您的 'Arrays' 应该是 char
数组而不是 int
。
char l1[n1];
char l2[n2];