简体   繁体   中英

Wrong calculation result on uint64_t

Context

Debian 64bits.

I have this code

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

int main(int argc, char ** argv){

    uint64_t b = 5000000000;/* 5 000 000 000 */
    uint64_t a = (b*b)/2;

    printf("a = %llu\n",a);

return 0;
}

Problem

Javascript, my hand calculator and the virtual calculator in my operating system give me a result of 1.25×10^19 whereas my c program above gives a = 3276627963145224192

What am I doing wrong ?

Your intermediate operation of b*b has value which is greater than what a 64-bit register can hold, hence it overflows.

Since, b (= 5 000 000 000) > 2^32 , hence, b*b > 2^64

And, since 5000000000 * 5000000000 / 2 can never fit into 64-bit variable, you cannot calculate this value in C without using special methods like representing number using arrays.

Also, as @Joachim Pileborg suggested, you should assign unsigned long long value to b as

uint64_t b = 5000000000ull;

uint64_t can't hold the result of b*b .

The result of b*b is 25000000000000000000. That is 25x10^18.

But uint64_t can hold maximum value upto 6553255926290448384. Hence overflow occurs in b*b operation.

Due to this overflow you are not getting the actual result!

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

int main(int argc, char ** argv){

    uint64_t b = 5000000000LL;/* 5 000 000 000 */
    uint64_t a = (((uint64_t)b)*b)/2LL;

    printf("a = %llu\n",a);

return 0;
}

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