简体   繁体   English

uint64_t的计算结果错误

[英]Wrong calculation result on uint64_t

Context 上下文

Debian 64bits. Debian 64位。

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 Javascript,我的手动计算器和操作系统中的虚拟计算器给我的结果是1.25×10 ^ 19,而我上面的c程序给出的是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. b*b中间操作的值大于64位寄存器可以容纳的值,因此它会溢出。

Since, b (= 5 000 000 000) > 2^32 , hence, b*b > 2^64 由于b (= 5 000 000 000) > 2^32 ,因此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. 而且,由于5000000000 * 5000000000 / 2永远无法放入64位变量中,因此,如果不使用特殊方法(如使用数组表示数字)就无法在C中计算该值。

Also, as @Joachim Pileborg suggested, you should assign unsigned long long value to b as 另外,正如@Joachim Pileborg所建议的那样,您应将unsigned long long值分配给b

uint64_t b = 5000000000ull;

uint64_t can't hold the result of b*b . uint64_t无法保存b*b的结果。

The result of b*b is 25000000000000000000. That is 25x10^18. b*b的结果是25000000000000000000。即25x10 ^ 18。

But uint64_t can hold maximum value upto 6553255926290448384. Hence overflow occurs in b*b operation. 但是uint64_t最多可以保留最大值6553255926290448384。因此,在b*b操作中会发生溢出。

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;
}

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

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