简体   繁体   中英

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)

#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 .

So the maximum positive number will be 2^31 = 2147483647 and minimum will be -2147483648

long int is sometimes 64 bits (as is on my PC) so its range will change. Max value will then be 9223372036854775807

According to your code,

  • If input is 2147483647 , then output = 10 . (Correct).

  • If input is 9223372036854775807 (max valid value) , then output =
    19 (Correct).

  • If input is 92233720368547758078 (exceeds max valid value and has number of digits as 20) , then
    output = 19 (Incorrect).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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