c語言中返回整數值的長度

小鲨鱼2018發表於2024-11-08

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

相關文章