C编程:如何检查给定的数字是否正好是数字,不多不少?

C编程:如何检查给定的数字是否正好是数字,不多不少?,c,C,C编程:如何检查给定的数字是否正好是数字,不多不少 我还是C编程新手。如果这是一个容易问的问题,很抱歉。只需检查数字的范围: int x = 4125; //this is just an example value ... if( (x >= 1000 && x <= 9999) || (x >= -9999 && x <= -1000) ){ //is valid }else{ //is not valid } int

C编程:如何检查给定的数字是否正好是数字,不多不少


我还是C编程新手。如果这是一个容易问的问题,很抱歉。

只需检查数字的范围:

int x = 4125; //this is just an example value ...
if( (x >= 1000 && x <= 9999) || (x >= -9999 && x <= -1000) ){
    //is valid
}else{
    //is not valid
}
intx=4125//这只是一个示例值。。。

如果((x>=1000&&x=-9999&&x如果您确实需要4位数字,则可以使用Tom Mekken给出的方法。 但如果您只想检查整数的位数,则始终可以使用以下方法:

floor (log10 (abs (x))) + 1

请记住,当数字为零时,它将不起作用,因此您必须在之前检查它。

这里有一个函数可以实现这一点

#include <stdio.h>

int f(int n);

int main(void)
{
    int n = 1234;
    int num_of_digits = f(n);
    if( num_of_digits == 4 )
    {
        printf("%d\n",num_of_digits);
    }
}

int f(int n)
{
    int num_of_digits = 0;
    while( n )
    {
        n /= 10;
        num_of_digits++;
    }
    return num_of_digits;
}
#包括
int f(int n);
内部主(空)
{
int n=1234;
int num_的_位数=f(n);
if(数字的数量=4)
{
printf(“%d\n”,数字的数量);
}
}
int f(int n)
{
int num_的_位数=0;
while(n)
{
n/=10;
位数++;
}
返回\u个数字的\u个;
}

我假设你是指四(4)位数字?当你说“for”时,你是指四位吗?在这种情况下,
数字>=1000&&number<10000
(假设为十进制).我假设'for'='four'…那么10000x==0
x==INT\u MIN