开发者

Capacity of a uint64_t?

I have a little problem. Essentially, the code:

uint64_t myInteger = 98930 * 98930;
NSLog(@"%qu", myInteger);

...just gets it wrong. I get '1197210308' as the output, whic开发者_如何学Goh is evidently incorrect. Why is this happening? It can't be that a uint64_t is too small, as they apparently go up to 18 and a half quintillion. Anyone have any idea?


Try casting the first number so the operation is made using that type:

uint64_t myInteger = (uint64_t)98930 *98930;


98930 is an int, so you're multiplying two ints, which gives an int. You're then assigning to a uint64_t, but it's too late, you've already lost the precision. Make sure one of the operands is of type uint64_t, so the other will be coerced to that type, and the multiplication will be done as uint64_t multiplication.


I don't know much about objective-C, but doing the same in C, integer promotions stop at the integer rank, so you get an integer overflow. Try:

uint64_t myInteger = 98930LLU * 98930;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜