c - 查找数组中重复的整数

标签 c arrays boolean

您好,我成功地检查了我的程序是否重复了 8。我还想打印出数组中存储了多少个重复的 8。

#include <stdio.h>
#include <stdbool.h>
int main(void)
{
    bool digit_seen[10] = {false};
    int digit=0;
    long n;

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

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

    if (n>0 && digit ==8)
    {
        printf("Repeated 8's");
    }
    else
    {
        printf("No 8's found");
    }
    return 0;
}

最佳答案

如果我理解你的问题,你想知道 8 在你的数字中出现的次数。就像 88 有 2 个 8。如果是这样的话,我不明白你为什么使用 boolean 数组。首先,你需要一个计数器。其次,您需要知道每个数字是否都是 8,如果是 8,则增加此计数器。下面是一个示例:

#include <stdio.h>
#include <stdbool.h>
int main(void)
{
    int digit=0;
    long n;
    int counter = 0;

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

    while (n>0)
    {
        digit = n % 10;
        if(digit == 8)
        {
            counter++;
        }

        n/=10;
    }

    if (counter > 0)
    {
        printf("Repeated 8's");
    }
    else
    {
        printf("No 8's found");
    }
    return 0;
}

在此示例中,计数器将记录您的数字中出现 8 的次数。只需将其显示在 printf 中即可完成。

编辑:这是使用数组的解决方案:

#include <stdio.h>

int main(void)
{
    int digit = 0;
    long n;
    int arrayNumber[10] = {0};

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

    while (n>0)
    {
        digit = n % 10;
        arrayNumber[digit]++;

        n /= 10;
    }

    if (arrayNumber[8] > 0)
    {
        printf("Repeated 8's");
    }
    else
    {
        printf("No 8's found");
    }
    return 0;
}

这样,您就可以知道整数中从 0 到 9 的每个数字的出现情况。我还想指出,您需要定义什么是重复数字。如果至少出现 2 次,则需要将 arrayNumber[8] > 0 更改为 arrayNumber[8] > 1

关于c - 查找数组中重复的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39935245/

相关文章:

c - 从文本文件中逐行读取信息

c - strtok() 作为 printf() 中的参数反向打印值

python - 与 ndarray 的矩阵乘法

c# - 单击 C# 中的按钮时变量会重新初始化

javascript - 如何避免 JavaScript 中的短路求值?

c++ - select() 在一个简单的自制 p2p 程序中与 udp 交换 "musicdata"的问题

c - 为什么 sem_open 在没有共享内存的情况下与 fork() 一起工作?

java - java UML图

java - 如何调用字符串数组中的 Java 方法? (java.lang.NoSuchMethodException)

javascript - 将一组 "true" boolean 值变量转换为数组