【问题标题】: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)并打印 L1 - L2 如果 L2 是 L1 的子数组的程序
【发布时间】:2021-11-13 16:27:54
【问题描述】:

我创建了这个程序,它从用户读取两个数组(L1 和 L2),如果 L2 是 L1 的子数组,则打印 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);
}```

【问题讨论】:

  • 如果 L1 是 {'a','a','b','a'} 而 L2 是 {'a'},应该打印什么?在这种情况下,是否应该打印:"b""a b a""a a b"?同样,如果 L1 是 {'a','a','b','a'} 而 L2 是 {'a', 'a'},它会打印什么?
  • “a b a”和“b a”分别
  • 你有:scanf("% c",&amp;l2[i]);。我很确定您不是要在%c 之间放置一个空格。同样的问题存在两次。
  • 是个错误,我现在改成" %c",但还是一样的问题
  • 当你想读取输入时不要使用scanf()。使用fgets(),然后使用sscanf() 解析结果。 scanf() 非常容易出错,你应该避免它。

标签: arrays c sub-array


【解决方案1】:

您的“数组”应该是 char 数组,而不是 int

char l1[n1];
char l2[n2];

【讨论】:

  • 谢谢!这是救命稻草。我明天有一个作业要交,这真的很有帮助
  • 没问题。祝你未来好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-29
  • 2020-06-02
  • 2013-01-20
  • 1970-01-01
  • 2010-11-09
  • 2019-10-26
  • 1970-01-01
相关资源
最近更新 更多