c - 如何显示在c中重复的数字?

标签 c

问题是显示在 C 中重复的数字。

所以我这样写:

#include<stdio.h>
#include<stdbool.h>

int main(void){

    bool number[10] = { false };
    int digit;
    long n;

    printf("Enter a number: ");
    scanf("%ld", &n);

    printf("Repeated digit(s): ");

    while (n > 0)
    {
        digit = n % 10;
        if (number[digit] == true)
        {
            printf("%d ", digit);
        }
        number[digit] = true;
        n /= 10;
    }

      return 0;
}

但它会一次又一次地显示重复的数字 (例如输入:55544 输出:455)

我修改了它:

#include<stdio.h>

int main(void){

    int number[10] = { 0 };
    int digit;
    long n;

    printf("Enter a number: ");
    scanf("%ld", &n);

    printf("Repeated digit(s): ");

    while (n > 0)
    {
        digit = n % 10;
        if (number[digit] == 1)
        {
            printf("%d ", digit);
            number[digit] = 2;
        }
        else if (number[digit] == 2)
            break;
        else number[digit] = 1;

        n /= 10;
    }
    return 0;
}

有效!

但是,我想知道如果我需要使用 bool 值(true false)或者更有效的方法怎么办?

最佳答案

要使您的第一个版本正常工作,您需要跟踪两件事:

  • 你见过这个数字吗? (检测重复项)
  • 你已经打印出来了吗? (只输出重复一次)

所以像这样:

bool seen[10] = { false };
bool output[10] = { false };

// [...]

  digit = ...;
  if (seen[digit]) {
    if (output[digit])) {
      // duplicate, but we already printed it
    } else {
      // need to print it and set output to true
    }
  } else {
    // set seen to true
  }

(一旦你让它工作了,你就可以简化 if。如果你把两个测试结合起来,只需要一个。)

您的第二个版本快完成了,但是太复杂了。您需要做的就是:

  • 每次看到该数字就在计数器上加一
  • 仅当计数器恰好为二时才打印数字。
digit = ...;
counter[digit]++;
if (counter[digit] == 2) {
  // this is the second time we see this digit
  // so print it out
}
n = ...;

附带的好处是您可以在末尾获得每个数字的计数。

关于c - 如何显示在c中重复的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26571077/

相关文章:

c++ - 无法使用 npapi 获取 DOM 窗口

编译器无法识别控制键,例如 C 中的 Return 键

c - 尝试在我的 shell 程序中实现警报。 C 信号处理

关于指针和数组的混淆

c - 使用结构传输变量

C Matrix redimensioning导致段错误

c - C中程序堆栈的确切内容是什么?

c - fseek 和 fwrite 过去的 EOF

c - 使用C语言命名linux机器的服务器IP

c - 在 Arduino 上使用 C 中 PROGMEM 中的结构函数指针