0

Im new to C++ and i'm not sure why the output for this code is 8 and not 8.25?

can someone explain why this code outputs an int not a double?

Thanks :)

#include "stdafx.h"
#include <iostream>


int main()
{

double x = 8.25;
    int y;
    y = x;

    double z = static_cast<double>(y);
    std::cout << z << std::endl;
return 0;
}
Kane B
  • 21
  • 2
  • 8 is a valid value for a double. You rounded 8.25, what did you expect exactly? – skypjack Feb 18 '17 at 09:33
  • You're doing an implicit cast to an int when you do y = x, so y won't have the decimals. Then when casting it back you're only casting back the 8. – Bozemoto Feb 18 '17 at 09:33
  • 1
    You guys *do* realise the difference between a comment and an answer, right? :-) Both of those looked like *answers* to me, unlike this (of dubious humour) comment. – paxdiablo Feb 18 '17 at 09:43
  • @paxdiablo You are right. I'm not on SO for reputation mining and such kind of questions usually receive answers anyway. That's why I put it in a comment, I didn't have time to turn it in an answer longer than 10 words. My fault. – skypjack Feb 18 '17 at 10:34
  • @skypjack: It's not just for reputation. Writing answers as answers also increases readability and (supposedly) findability on Google. – Christian Hackl Feb 18 '17 at 11:54
  • 1
    @ChristianHackl Yeah. As I said, it was mainly me short in time to formulate properly an answer and I was sure that such a question would have received an answer anyway. – skypjack Feb 18 '17 at 12:00
  • 2
    @Bozemoto -- the code has an **implicit conversion**. There is no such thing as an implicit cast; a cast is something you write in your source code to tell the compiler to do a conversion. – Pete Becker Feb 18 '17 at 12:42
  • @PeteBecker Right you are, english isn't my first language so got the terms mixed up. Thanks for clearing that up. – Bozemoto Feb 18 '17 at 15:51

1 Answers1

5

The data is converted to the integer 8 in the statement y = x.

A static_cast cannot recover the lost ".25" after throwing it away by converting to int.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
MikeCAT
  • 73,922
  • 11
  • 45
  • 70