D
D
Daniil Demidko2016-03-11 09:56:42
C++ / C#
Daniil Demidko, 2016-03-11 09:56:42

Functional type casting?

I'm aware of type casting, old-style and functional, static_cast and dynamic_cast, but I don't want to ask about that.
Why does this seemingly identical code work differently?

// Старый / Си стиль
std::cout<< (double) 1 / 3 ; // Что то вроде 0.3333333

// Функциональный стиль
std::cout<< double (1 / 3) ; // Почему 0 ?

What about the second example?
It seems to create a temporary variable double, almost the same as in the first case, but why is 0 displayed?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
res2001, 2016-03-11
@Daniro_San

In the first case, 1 is first converted to double explicitly, then 3 is implicitly converted to double, because the first argument of the operation is double, and then the division of two doubles is performed.
In the second case, an integer division is performed with the result 0, then 0 is reduced to a double.

A
Alexey Yeletsky, 2016-03-11
@Tiendil

Here are a couple of equivalent examples

// Что то вроде 0.3333333
std::cout<< (double) 1 / 3 ; 
std::cout<< double(1) / 3 ;

std::cout<< double (1 / 3) ; 
std::cout<< (double) (1 / 3) ;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question