计算C中一个整数中特定数字的出现 [英] Counting occurance of a specific number in an integer in C
问题描述
我遇到了一些麻烦...我试图输入一个数字,然后输入多个数字的整数.我试图计算第一个数字在整数中出现了多少次.现在,我编写了这个非常简单的代码,向您展示了我实际上正在尝试做的事情.关键是,此代码仅比较两个整数,并告诉我它们是否相同.请注意,我对C编程非常缺乏经验,因此这个问题...
I'm having some troubles... I'm trying to input a number, followed by an integer of multiple numbers. I am trying to count how many times the first number occurs in the integer. Now, I made this really easy code to show you what I actually am trying to do. The thing is, this code only compares two integers and tells me if they are the same or not. Mind you, I am very unexperienced in C programming, hence this question...
int main(){
int numberOne;
int numberTwo;
int count = 0;
scanf("%d", &numberOne);
scanf("%d", &numberTwo);
if(numberOne == numberTwo){
count++;
}
printf("Amount of equals found: %d", count);
return 0;
}
现在,如果我有以下输入:'1 1021023234',则输出将是:'发现的等于数量:0'输出(在这种情况下)应为输出将为等于找到的数量:2"
Now, if I'd have the following input: '1 1021023234', the output would be: 'Amount of equals found:0' The output should be (in this case) 'The output would be Amount of equals found:2'
我希望你们能给我一些提示.
I hope you guys can give me some tips.
推荐答案
如果我正确理解,则需要以下内容
If I have understood correctly then you need the following
#include <stdio.h>
int main(void)
{
unsigned int numberOne;
unsigned int numberTwo;
unsigned int x;
unsigned int base;
size_t n;
printf( "Enter first number: " );
scanf( "%u", &numberOne );
printf( "Enter second number: " );
scanf( "%u", &numberTwo );
x = numberOne;
base = 1;
do { base *= 10; } while ( x /= 10 );
n = 0;
do { n += numberOne == numberTwo % base; } while ( numberTwo /= 10 );
printf( "Amount of equals found: %u", n );
return 0;
}
对于数字 12
和 76512612
,输出为
Amount of equals found: 2
这篇关于计算C中一个整数中特定数字的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!