试图弄清楚为什么我的 C 程序只抓取我重复的数字之一

Trying to figure out why my C program is only grabbing one of my repeated digits

我正在编写一个 C 程序,它将接受用户输入,然后打印出输入的重复数字。


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

int main(void)
{
    
    bool digit_seen[10] = {false};
    int digit;
    long n;
    

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

    while (n > 0)
    {
        digit = n % 10;
        
        if (digit_seen[digit])
            break;
             
        digit_seen[digit] = true;
        
        n /= 10;
    }

    if (n > 0) {
        printf("Repeated digit(s): ");
        for (int x = 0; x < 10; x++){
            
            if (digit_seen[x] == true){
                printf("%d", x);
            }
        }
        
    }
    else {
        printf("No repeated digit\n");
    }



   

    return 0;
}

输出是Repeated Digits:7,我输入了939577 输出是Repeated Digits:56,我输入了5656

好像只抓到最后几个号,但我不明白为什么。我希望它能够获取所有重复的数字。我希望答案看起来像 Repeated Digits:7 9输入939577后

如有任何帮助,我们将不胜感激。

目前您只是检查每个数字是否存在,并在找到第一个重复数字时停止检查。

不仅在 939577 中找到 9,您的程序将打印 Repeated Digits:123 用于输入 1123 而 2 和 3 不是重复数字。

除此之外,您应该计算每个数字并将发现两个或更多个数字的数字报告为重复数字。

还需要进行一些调整以使输出与预期相匹配。

试试这个:

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

int main(void)
{
    
    int digit_seen[10] = {0};
    int digit;
    bool repeated_exists = false;
    long n;
    

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

    while (n > 0)
    {
        digit = n % 10;
        
        digit_seen[digit]++;
        if (digit_seen[digit] > 1) repeated_exists = true;
        
        n /= 10;
    }

    if (repeated_exists) {
        bool is_first_repeated = true;
        printf("Repeated digit(s):");
        for (int x = 0; x < 10; x++){
            
            if (digit_seen[x] > 1){
                if (!is_first_repeated) printf(" ");
                printf("%d", x);
                is_first_repeated = false;
            }
        }
        
    }
    else {
        printf("No repeated digit\n");
    }

    return 0;
}