c语言4-12 输入一个整数值显示其位数

 

1、while语句

#include <stdio.h>

int main(void)
{
    int i, cnt = 0;
    puts("please input an integer.");
    do
    {
        printf("i = "); scanf("%d", &i);
        if (i <= 0)
            puts("the range of i is : > 0");
    }
    while (i <= 0);
    
    printf("the span number of %d is: ", i);
    while (i > 0)
    {
        i /= 10;
        cnt++;
    }
    printf("%d\n", cnt);
    
    return 0;
}

 

2、for语句

#include <stdio.h>

int main(void)
{
    int i, cnt = 0;
    puts("please input an integer.");
    do
    {
        printf("i = "); scanf("%d", &i);
        if (i <= 0)
            puts("the range of i is: > 0");
    }
    while (i <= 0);
    
    printf("the span number of %d is: ", i);
    for (i; i > 0; i /= 10)
    {
        cnt++;
    }
    printf("%d\n", cnt);
    
    return 0;
}

 

3、do语句

#include <stdio.h>

int main(void)
{
    int i, cnt = 0;
    puts("please input an integer.");
    do
    {
        printf("i = "); scanf("%d", &i);
        if (i <= 0)
            puts("the range of i is : > 0");
    }
    while (i <= 0);
    
    printf("the span number of %d is: ", i);
    do
    {
        cnt++;
        i /= 10;
    }
    while (i > 0);
    printf("%d\n", cnt);
    
    return 0;
}

 

posted @ 2021-04-19 17:42  小鲨鱼2018  阅读(482)  评论(0编辑  收藏  举报