简体   繁体   中英

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

I am writing a C program that will take user input and then print out what repeated digits were inputted.


#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;
}

The output is Repeated Digits:7 and I inputted 939577 The output is Repeated Digits:56 and I inputted 5656

It seems that it is only grabbing the last few numbers but I do not understand why. I want it to be able to grab all repeated digits. I want the answer to look like Repeated Digits:7 9 after inputting 939577

Any help would be appreciated.

Currently you are simply checking if each digits exists and stop checking when the first repeated digit is found.

Not only finding 9 in 939577 , your program will print Repeated Digits:123 for input 1123 while 2 and 3 are not repeated digits.

Instaed of this, you should count each digits and report digits that found two or more as repeated digits.

Also some more tweaks are needed to match the output to the expected one.

Try this:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM