表达式计算不正确

问题描述

我编写了这段代码,可以正确评估所有内容,直到获得这组特定的数字为止:

#include <cmath>

int n1 = 187972 ;
int n2 = 12026 ;
double a = 0.002 ;
int partial = round((n1*n2)*a) ;
int result = n1 - partial ;

结果由程序返回为4256804,这是完全错误的。我想我弄错了,但我看不出怎么办。

解决方法

如建议的注释中所示,结果是正确的,因为n1 * n2正在溢出int最大值,由于溢出而产生负数

实际上是-2034416024

此处为ideone,因此您可以进行验证

https://ideone.com/NIGCmx

一种解决方案可以改用长数字

,
#include <cmath>

int n1 = 187972 ;
int n2 = 12026 ;
double a = 0.002 ;
long long partial = round((n1*n2)*a) ;   // new
long long result = n1 - partial ;   // new