如何在C中找到一个长的长度(位数)?

问题描述 投票:-1回答:3

这是提示用户输入的代码

#include <stdio.h>
#include <cs50.h>

//prompt user for number

int main(void)
{
      long number = get_long("Enter card number: "); 
}
c long-integer
3个回答
1
投票

以下程序将为您提供帮助,但它的下注者需要付出一些努力

     #include <stdio.h>
     #include <cs50.h>

        //prompt user for numb er

    int main(void)
    {
        long number = get_long("Enter card number: "); 
        int count = 0; 
        do{ 
            number = number / 10; 
            ++count; 
        }while (number != 0) ;

        printf("length of number = %d",count);

    }

1
投票

[如果您允许自己使用浮点,则以A为底的正整数B的位数是以B为底的A的对数加1。以10为底,您可以编写:

long get_num_digits(long a)
{
    long c;

    if (a == 0) {
        return 1;
    }
    if (a < 0) {
        a = -a;
    }
    c = (long)log10((double)a);
    ++c;

    return c;
}

1
投票

您可以例如:

#include <stdio.h>
#include <string.h>
void main()
{
    long alpha = 352;
    char s[256];
    sprintf(s,"%ld",(alpha >= 0L) ? alpha : -alpha );
    printf("long digits: %lu",strlen(s));

}
© www.soinside.com 2019 - 2024. All rights reserved.