C语言 如何检查 int var 是否包含特定数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4977456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:45:43  来源:igfitidea点击:

How to check if a int var contains a specific number

cnumberscharint

提问by c5754272

How to check if a int var contains a specific number

如何检查 int var 是否包含特定数字

I cant find a solution for this. For example: i need to check if the int 457 contains the number 5 somewhere.

我找不到解决方案。例如:我需要检查 int 457 是否在某处包含数字 5。

Thanks for your help ;)

谢谢你的帮助 ;)

回答by matt.dolfin

457 % 10 = 7    *

457 / 10 = 45

 45 % 10 = 5    *

 45 / 10 = 4

  4 % 10 = 4    *

  4 / 10 = 0    done

Get it?

得到它?

Here's a C implementation of the algorithm that my answer implies. It will find any digit in any integer. It is essentially the exact same as Shakti Singh's answer except that it works for negative integers and stops as soon as the digit is found...

这是我的答案所暗示的算法的 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;
    }
}

回答by Yhrn

Convert it to a string and check if the string contains the character '5'.

将其转换为字符串并检查该字符串是否包含字符“5”。

回答by Shakti Singh

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