2015-12-02 10 views
5

私は幅888ピクセル、高さ592ピクセル、幅:高さのアスペクト比が3:2のイメージを持っています。Visual Studio 2015では、「キャストは冗長です」と表示されています。どうして?

以下が原因BitmapDecoder.PixelWidthとBitmapDecoder.PixelHeightとして整数演算/トランケーションにより、1の間違った値を生成するには、両方のuint(符号無し整数)、及びBitmapDecoderオブジェクトである以下decoderです。

double aspectRatio = decoder.PixelWidth/decoder.PixelHeight;

以下は1.5の期待正しい値が得られますが、Visual Studioは、「キャストが冗長である」と言うが、なぜ?

double aspectRatio = (double)decoder.PixelWidth/(double)decoder.PixelHeight;

+1

あなただけの1(ダブル)キャストを必要とします - double/int = doubleです。またはint/double = double。 – Dmitriy

+0

doubleを任意の数値型で分割すると、結果は常にdoubleになります。 –

+0

'double aspectRatio = static_cast (decoder.PixelWidth)/ decoder.PixelHeight;は、コンパイラが' PixelHeight'をdoubleとして使用するのに十分なはずです。 – Pixelchemist

答えて

12

は、あなただけの浮動小数点演算を強制的に倍増するするuintのをキャストする必要がありますので、次のいずれか

double aspectRatio = decoder.PixelWidth/(double)decoder.PixelHeight; 

か:個人的に

double aspectRatio = (double)decoder.PixelWidth/decoder.PixelHeight; 

、I後者と一緒に行くが、それは意見の問題である。ただ、ChrisFの答え@補完する

+1

取得する! 1つのキャストで十分でしたが、Visual Studioは私をトラックから離しました。私はVisual Studioが最初のキャストを残しておき、2番目のキャストを絶対的に正確である必要がないものとしてレンダリングしたいと思います。その意味では、Visual Studioは少し誤解を招いていますが、その理由を説明することができます。 – user2921851

2

、あなたはdoubleへの単一のキャストが両方の値の変換をもたらすILコードでうまくこれを見ることができます:

IL_0013: stloc.0  // decoder 
IL_0014: ldloc.0  // decoder 
IL_0015: callvirt UserQuery+Decoder.get_PixelHeight 
IL_001A: conv.r.un // convert uint to float32 
IL_001B: conv.r8  // convert to float64 (double) 
IL_001C: ldloc.0  // decoder 
IL_001D: callvirt UserQuery+Decoder.get_PixelWidth 
IL_0022: conv.r.un // convert uint to float32 
IL_0023: conv.r8  // convert to float64 (double) 
関連する問題