且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

与价值不一致

更新时间:2023-02-13 13:07:05

您需要确保代码以正确的顺序进行评估,请参见C++中的运算符优先级 [double val ; val = cos(-0.00623381826089208+90/180*3.14159265358979)*12.85+cos(-0.00623381826089208)*(-49.72)+6767250.28012434;



The c++ result is 6767200.5623347033,  but the excel result shows:  6767200.641. SO I split it and compared a part of the formula,
val = cos(-0.0062338182608920800000+90/180 *3.14159265358979000);
 but again, this shows 0.006233778 in excel and 0.99998056981786743 in c++



This makes a huge difference in further calculations. Another thing I observed was the line val = cos(20) or val = cos(10) gives compiler error and cos can take only small numbers like 0.2, 0.9. The error I get is "more than one instance of overloaded function "cos" matches the argument list"

Need some help please..

You need to make sure your code is evaluating in the correct order, see the rules of Operator precedence in C++[^] for guidance. You also need to check which version of the cos() function you are using, the compiler messages suggest it has a number of overloads. You may also find discrepancies owing to the way that floating point values are represented in computing and how accuracy can be a problem; a Google search will get you lots of articles on the subject.


I believe Excel considers argument of cos() function to be in radians while C++ treats it as degrees. Also, as Richard noted, check operator precedence in complex expressions like 90/180*3.14159265358979000, and make sure you divide float values, no ints


Watch the operator precedence and type casting rules! The term

90/180



delivers in C++ the value of 0, as it is an int division. Excel will probably convert both 90 and 180 to double first and comes to a result of 0.5.

Try writing 90./180. in your C++ expression and see the difference.

Also: Your expression is numerically not very stable. You arr adding something in the range of 50 to a value of 6767250. That''s 5 orders of magnitude difference. In type float you would probably get a totally erratic result. In double things run somewhat better, but don''t expect the result to have more than 15 - 5 = 10 significant digits.