打印整数的位数

问题描述 投票:-2回答:1

我必须提交此代码,目的是计算数字的数字并打印它(范围从-231 + 1到231-1),结果必须显示为单个数字(例如,给定数字234它打印3)

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    long int num_ins;
    int contador = 0;

    printf("Inserir numero desejado a avaliar?\n"); // asking the number
    scanf("%ld", &num_ins);

    if (num_ins == 0) {
        printf("%d", 1);
    } else {
        while (num_ins != 0) {
            num_ins = num_ins / 10;
            contador++;
        }
        printf("%d", contador); //contador is count
    }
}

但是提交的内容一直给我一个错误,有些数字表示不对,我无法弄清楚。

c
1个回答
0
投票

首先,如果您使用的是32位数据类型,则范围将为-2^31 to 2^31 -1

所以最大正数将是2^31 = 2147483647,最小值将是-2147483648

long int有时是64位(就像在我的电脑上一样)所以它的范围会改变。最大值将是9223372036854775807

根据你的代码,

  • 如果输入是2147483647,则输出= 10。 (正确)。
  • 如果输入是9223372036854775807(最大有效值),则输出= 19(正确)。
  • 如果输入是92233720368547758078(超过最大有效值并且位数为20),那么 output = 19(不正确)。
© www.soinside.com 2019 - 2024. All rights reserved.