简体   繁体   中英

Parsing a number with more than 10 digits in C

I'm trying to calculate UPC codes using C as a language, but I'm now having a problem with the precision. I tried int, float, long long, etc.

Here's the code:

#include <stdio.h>

int main(void)
{
    float upc;

    printf("Enter UPC:\n");
    scanf ("%d", &upc);
    printf("upc = %f ", upc);
}

the results are :

Enter UPC code:
123456789012
upc = 123456790528.000000 d= 1
Process returned 30 (0x1E)   execution time : 6.672 s
Press any key to continue.

How can I show the number as is? It's only 12 digits. I'm using CodeBlocks, is there an IDE that can handle this better?

Note: please don't tell me to just use char ! I want to make some calculations later.

Universal product codes are not subject to integer arithmetic operations, so it doesn't entirely make sense to represent them using int . Each digit is assigned a particular meaning , so a string makes more sense.

If you really just want a band-aid, uint64_t from <stdint.h> will always be able to hold a 12-digit number. Do not use a floating-point type, though, as they are not designed to hold exact integers, but rather to approximate real numbers.

The correct way to use uint64_t with printf and scanf is with the fixed-width format specifiers from <inttypes.h> :

scanf ( "%" SCNd64, &upc);
printf("upc = %" PRId64 "\n", upc);

A float can typically store just 6-7 decimal digits. A 32-bit int can store 9 digits (10 if the leading digits is 3 or less). To store a 12-digit integer, you need to use either a long long (up to 18 digits) or perhaps a double (up to 15-16 digits), though a double is less desirable.

Hence:

#include <stdio.h>

int main(void)
{
    long long upc;

    printf("Enter UPC:\n");
    scanf ("%lld", &upc);
    printf("upc = %lld\n", upc);
    return(0);
}

Actually can you be more clear of what you want as your output? I suggest you one modification in to use long long int instead of float.

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