如何避免expr中的溢出.A B C D

编程入门 行业动态 更新时间:2024-10-24 20:16:01
本文介绍了如何避免expr中的溢出.A B C D的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要计算一个看起来像这样的表达式: A * B-C * D ,其类型为: signed long long int A,B,C,D; 每个数字可能确实很大(不会溢出其类型).虽然 A * B 可能会导致溢出,但同时 A * B-C * D 表达式可能确实很小.如何正确计算?

I need to compute an expression which looks like: A*B - C*D, where their types are: signed long long int A, B, C, D; Each number can be really big (not overflowing its type). While A*B could cause overflow, at same time expression A*B - C*D can be really small. How can I compute it correctly?

例如: MAX * MAX-(MAX-1)*(MAX + 1)== 1 ,其中 MAX = LLONG_MAX-n 和n-一些自然数字.

For example: MAX * MAX - (MAX - 1) * (MAX + 1) == 1, where MAX = LLONG_MAX - n and n - some natural number.

推荐答案

我想这似乎太琐碎了.但是 A * B 可能会溢出.

This seems too trivial I guess. But A*B is the one that could overflow.

您可以执行以下操作,而不会失去精度

You could do the following, without losing precision

A*B - C*D = A(D+E) - (A+F)D = AD + AE - AD - DF = AE - DF ^smaller quantities E & F E = B - D (hence, far smaller than B) F = C - A (hence, far smaller than C)

此分解可以进一步完成.正如@Gian指出的那样,如果类型为unsigned long long,则在减法操作期间可能需要小心.

This decomposition can be done further. As @Gian pointed out, care might need to be taken during the subtraction operation if the type is unsigned long long.

例如,在您遇到问题的情况下,只需进行一次迭代,

For example, with the case you have in the question, it takes just one iteration,

MAX * MAX - (MAX - 1) * (MAX + 1) A B C D E = B - D = -1 F = C - A = -1 AE - DF = {MAX * -1} - {(MAX + 1) * -1} = -MAX + MAX + 1 = 1

更多推荐

如何避免expr中的溢出.A B C D

本文发布于:2023-11-30 05:26:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648873.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:expr

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!