您好,我成功地检查了我的程序是否重复了 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/