プログラミング+α学習ブログ

勉強したことの備忘録です。

読み込んだ非負の整数値の桁数を求めるプログラム

#include <stdio.h>

int main(void)
{
    int num, temp;
    int dig;    // 桁数
    
    do {
        printf("非負の整数を入力してください:");
        scanf("%d", &num);
        if (num < 0)
            puts("負の数を入力しないでください。");
    } while (num < 0);
    
    temp = num;
    dig = 0;
    
    do {
        temp = temp / 10;   // 右に1桁ずらす
        dig = dig + 1;
    } while (temp > 0);
    printf("%d%d桁です。\n", num, dig);
    
    return (0);
}

実行結果

非負の整数を入力してください:1963
1963は4桁です。