質問

いくつかの理由で、ダブルの代わりにフロートをコードに使用する必要があります。私のコードで文字通りを使用するには、次のようなものを書く必要があります。

float f = 0.75F;

または、コンパイラは「0.75」をダブルとして扱うため、BARFになります。コードに入れることができるものや、「0.75」のような文字通りをフロートとして扱うことなく、「F」を毎回追加することなくフロートとして扱うことができるものはありますか?

役に立ちましたか?

解決

floatにはfが付属しています:-)

他のヒント

いいえ - 幸いなことに、IMO。リテラルはどこでも同じ方法で扱われます。

これは良いことです - メンテナンス開発者が来て、1年後にあなたのコードを見ることを想像してください。彼は「0.75」を見て、「私はC#を知っている - それは二重だ!ハングアップ、フロート変数にどのように割り当てられているのか」と考えています。 ICK。

どこにでも「F」を追加するのは本当にとても苦痛ですか?あなたは本当に持っていますか それ 多くの定数?それらを抽出していただけませんか なので 一定の値なので、すべての「f-suffixed」リテラルは同じ場所にあります。

参考までに - c#のすべてのコンパイラオプションを見つけることができます http://msdn.microsoft.com/en-us/library/6ds95cz0.aspx. 。そこで確認すると、これを許可するオプションがないことがわかります。

The language interprets floating point precision literals as doubles everywhere. This is not a configurable feature of the compiler - and with good reason.

Configuring how the language interprets you code would lead to problems with both compatibility and the ability of maintenance developers to understand what the code means.

While not advisable generally, you can reduce the pain a little in C# 3 by using:

var f = 0.75F;

Just be careful, because forgetting the 'F' suffix with this syntax WILL cause the compiler to create a double, not a float.

I would advise you to always use

var meaning = 1f;

because the "var" keyword saves a lot of human interpretation and maintenance time.

The proper behavior would not be for a compiler to interpret non-suffixed literals as single-precision floats, but rather to recognize that conversions from double to float should be regarded as widening conversions since, for every double value, there is either precisely one unambiguously-correct float representation, or (in a few rare edge cases) there will be precisely two equally-good values, neither of which will be more than a part per quadrillion from being the unambiguously-correct value. Semantically, conversions from float to double should be regarded as narrowing conversions (since they require that the compiler "guess" at information it doesn't have), but the practical difficulties that would cause might justify making conversions in that direction 'widening'.

Perhaps one should petition Microsoft to add a widening conversion from double to float? There's no good reason why code which calculates graphics coordinates as double should be cluttered with typecasts when calling drawing functions.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top