Is there a way in C++ to have it evaluate each floating point operation as a double even if the arguments are int? I have a program and numerous places I have code such as 1/2, 5/6. In these cases C++ casts the result to an int, that screws up the whole calculation. From the perspective of financial computations, are there other libraries besides ‘cmath’ that I could use that would contain more advanced functions.
Share
In C (and thus C++) all builtin operators (ie POD) operato on objects of the
same type. Thus if the parameters of a builtin operator have different types then the compiler will implicitly cast one (usually) of them (according to well defined rules) so that they are both the same. The result of the operator is also the same type as the input parameters.What you are seeing is integer division which returns an integer.
The implicit casting rules:
Note: All arithmatic operation are done on at least int. This means if both parameters are (u)short and/or char then they are both cast to int.
From this we can we can see that to get the operation to happen on doubles then at least one of the parameters must be a double in the code. To do this just add a fractional part to the expression.