[英]Why does this cause an overflow?
It's my understanding that uint64_t defined by C99 (stdint.h) is defined to be 8 bytes (= 64 bits) of length, thus allowing for a maximum value of 2^64 - 1. However, when I try the following code snippet, the uint64_t overflows, even though it's nowhere near 2^64 - 1:据我了解,由 C99 (stdint.h) 定义的 uint64_t 定义为 8 个字节(= 64 位)的长度,因此允许最大值为 2^64 - 1。但是,当我尝试以下代码片段时, uint64_t 溢出,即使它远不接近 2^64 - 1:
uint64_t Power10(int exponent)
{
int i = 1;
uint64_t ret = 10;
while(i < exponent)
{
ret *= 10;
++i;
}
return ret;
}
Help would be very much appreciated.帮助将不胜感激。
You need to print with "%" PRIu64
conversion.您需要使用
"%" PRIu64
转换打印。 Don't forget to add the right include!不要忘记添加正确的包含!
#include <inttypes.h>
int main(void) {
printf("Power10(12) is %" PRIu64 "\n", Power10(12));
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.