Afficher un message
Vieux 30/06/2008, 22h58   #5
Ivan Novick
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Implicit conversion from int to double

On Jun 30, 1:45pm, Sjouke Burry <burrynulnulf...@ppllaanneett.nnlll>
wrote:
> Jerry Coffin wrote:
> > In article <da23fd45-4729-4a98-8a99-
> > b9ef4dd88...@l28g2000prd.googlegroups.com>, ampheta...@gmail.com says....
> >> I know this might seem kind of silly, but is it necessary to cast int
> >> to double?

>
> >> Do I have to do

>
> >> int i = 42;
> >> double d = static_cast<double>(i);

>
> >> or can I just do d = i?

>
> > The language allows you to do the assignment without an explicit type
> > cast. Somewhere, I suppose there might be a compiler that warns you
> > about doing it, but that's a bit hard to guess -- someday I might create
> > a web site of "inane compiler warnings", but I haven't yet...

>
> My compileer warns, when losing precision,
> so d=i is oke, i=d gives warning(warning level set high).


This is covered in the C++ standard 4.9 "floating-integral
conversions".

Converting from an int to double should be pretty intuitive. The rule
when converting from double to int is to truncate the value.
Technically, the compiler should not have to warn in this case, but i
guess the compiler team felt normally this was an error in coding when
someone truncates by assigning a floating point to an integer.

Ivan Novick
http://www.mycppquiz.com
  Réponse avec citation
 
Page generated in 0,06538 seconds with 9 queries