C++ converting double to int in mathematical calculations

  • A+
Category:Languages

When I write cout<<3.0/2.0; I get 1.5 but when I write cout<< 3.0*2.0; I get 6. And if 3.0 and 2.0 are double values, shouldn't my result be a double value like 6.0? According to what is the result int or double?

 


The result of 3.0 * 2.0 is very much a double(a). However, the presentation of a value is not the value. You'll find that 6, 6.0, 6.00000, 0.06E2, 6000E-3 and even the symbolic -6(epi×i) are all the same value, with different presentations.

If you don't want the default presentation(b), the iostream and iomanip headers have facilities to format numbers in specific formats, such as using this to get 6.0:

#include <iostream> #include <iomanip> int main() {     auto x = 3.0 * 2.0;     std::cout << std::setprecision(1) << std::fixed << x << '/n'; } 

(a) The usual arithmetic conversions specified in the standard come into play here (eg, C++17 8 Expressions /11):

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

  • If either operand is of scoped enumeration type, no conversions are performed; if the other operand does not have the same type, the expression is ill-formed.
  • If either operand is of type long double, the other shall be converted to long double.
  • Otherwise, if either operand is double, the other shall be converted to double.
  • Other irrelevant stuff in the context of this question.

(b) The actual rules for what gets printed by default are specified in the standard, but complex and locale-aware enough that it's probably easier for most people to just do explicit formatting :-)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: