Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ converting double to int in mathematical calculations

Tags:

c++

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?

like image 834
Crazy_Boy53 Avatar asked Oct 30 '18 08:10

Crazy_Boy53


2 Answers

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 :-)

like image 59
paxdiablo Avatar answered Sep 24 '22 02:09

paxdiablo


The rules for what the output data type is from a given arithmetic operation are well defined in C++. You can find it out at compile time by using typeid.

std::cout << typeid(3.0 * 2.0).name() << std::endl; // Prints 'd' for double instead of 'i' for integer

You might be surprised to find out that adding two values of one data type (char) can result in an output of a different data type:

std::cout << typeid('a'+'b').name() << std::endl; // Prints 'i' for integer instead of 'c' for character

In this case, you are explicitly stating that 2.0 and 3.0 are floating point types. The result is, unsurprisingly, also a floating point type. However, the cout utility is omitting the decimal point because the result is a whole number.

like image 37
JimPri Avatar answered Sep 22 '22 02:09

JimPri