简体   繁体   English

打印整数的位数

[英]Printing the number of digits of an integer

I have to submit this code, the intention is to count the digits of a number and print it (range is from -2 31 +1 to 2 31 -1) and the result must be presented as a single number (for example, given the number 234 it prints 3)我必须提交这个代码,目的是计算一个数字的位数并打印它(范围是从-2 31 +1到2 31 -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
    }
}

But the submission keeps giving me an error, that there are some numbers where it isn't right, and I can't figure it out.但是提交一直给我一个错误,有一些数字不正确,我无法弄清楚。

First of all, if you are using a 32 bit data type, then the range will be -2^31 to 2^31 -1 .首先,如果您使用的是 32 位数据类型,那么范围将是-2^31 to 2^31 -1

So the maximum positive number will be 2^31 = 2147483647 and minimum will be -2147483648所以最大正数将是2^31 = 2147483647最小将是-2147483648

long int is sometimes 64 bits (as is on my PC) so its range will change. long int有时是 64 位(就像在我的 PC 上一样)所以它的范围会改变。 Max value will then be 9223372036854775807最大值将是9223372036854775807

According to your code,根据你的代码,

  • If input is 2147483647 , then output = 10 .如果输入是2147483647 ,则输出 = 10 (Correct). (正确的)。

  • If input is 9223372036854775807 (max valid value) , then output =如果输入是9223372036854775807 (max valid value) ,则输出 =
    19 (Correct). 19 (正确)。

  • If input is 92233720368547758078 (exceeds max valid value and has number of digits as 20) , then如果输入为92233720368547758078 (超过最大有效值且位数为 20),则
    output = 19 (Incorrect).输出 = 19 (不正确)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM