繁体   English   中英

试图弄清楚为什么我的 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;
}

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

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

任何帮助,将不胜感激。

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

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

相反,您应该计算每个数字并将找到两个或更多数字的数字报告为重复数字。

还需要进行更多调整以使 output 与预期匹配。

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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