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 @   小鲨鱼2018  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2023-11-08 The following perl modules required by RepeatModeler are missing from your system. Please install these first: JSON; JSON::PP; File::Which
2023-11-08 Warning: prerequisite Test::More 0 not found.
2023-11-08 Can't locate ExtUtils/MakeMaker.pm in @INC (@INC contains:
2022-11-08 python 中 lambda函数
2022-11-08 python 中 format函数
2022-11-08 python 中any 和 all函数
2022-11-08 python中数值处理函数
点击右上角即可分享
微信分享提示