c语言中返回整数值的长度

 

001、方法1

while循环

[root@PC1 test]# ls
test.c
[root@PC1 test]# cat test.c             ## 测试c程序
#include <stdio.h>

int get_length(int a)
{
        int length = 0;

        while(a > 0)
        {
                length++;
                a /= 10;
        }

        return length;
}

int main(void)
{
        int a;

        printf("a = "); scanf("%d", &a);

        printf("the length of %d is %d\n", a, get_length(a));

        return 0;
}
[root@PC1 test]# gcc test.c -o kkk                  ## 编译
[root@PC1 test]# ls
kkk  test.c
[root@PC1 test]# ./kkk
a = 3456
the length of 3456 is 4
[root@PC1 test]# ./kkk
a = 34
the length of 34 is 2
[root@PC1 test]# ./kkk
a = 354676
the length of 354676 is 6
[root@PC1 test]# ./kkk
a = 6
the length of 6 is 1

 。

 

002、方法2

do...while

[root@PC1 test]# ls
test.c
[root@PC1 test]# cat test.c            ## 测试c程序
#include <stdio.h>

int get_length(int a)
{
        int length = 0;

        do
        {
                length++;
                a /= 10;
        }
        while(a > 0);

        return length;
}

int main(void)
{
        int a;

        printf("a = "); scanf("%d", &a);

        printf("the lenght of %d is %d\n", a, get_length(a));

        return 0;
}
[root@PC1 test]# gcc test.c -o kkk            ## 编译
[root@PC1 test]# ls
kkk  test.c
[root@PC1 test]# ./kkk
a = 345
the lenght of 345 is 3
[root@PC1 test]# ./kkk
a = 4365346
the lenght of 4365346 is 7
[root@PC1 test]# ./kkk
a = 2
the lenght of 2 is 1

 。

 

posted @ 2024-11-08 23:07  小鲨鱼2018  阅读(2)  评论(0编辑  收藏  举报