如何检查int变量是否包含特定数字
我找不到解决方案。例如:我需要检查int 457中是否包含数字5。
谢谢您的帮助 ;)
457 % 10 = 7 *
457 / 10 = 45
45 % 10 = 5 *
45 / 10 = 4
4 % 10 = 4 *
4 / 10 = 0 done
理解了吗?
这是一个C语言实现的算法,可以找到任何整数中的任何数字。它基本上与Shakti Singh的答案完全相同,只是它适用于负整数,并且一旦找到数字就会停止...
const int NUMBER = 457; // This can be any integer
const int DIGIT_TO_FIND = 5; // This can be any digit
int thisNumber = NUMBER >= 0 ? NUMBER : -NUMBER; // ?: => Conditional Operator
int thisDigit;
while (thisNumber != 0)
{
thisDigit = thisNumber % 10; // Always equal to the last digit of thisNumber
thisNumber = thisNumber / 10; // Always equal to thisNumber with the last digit
// chopped off, or 0 if thisNumber is less than 10
if (thisDigit == DIGIT_TO_FIND)
{
printf("%d contains digit %d", NUMBER, DIGIT_TO_FIND);
break;
}
}
int i=457, n=0;
while (i>0)
{
n=i%10;
i=i/10;
if (n == 5)
{
printf("5 is there in the number %d",i);
}
}
while (i != 0)
,这样它也可以处理负数。 - akira
int
值457
并不真正“包含”数字5
。它的十进制表示包含了该数字。 - Keith Thompson