开发者

C# - Data Type for value 0.5

I have a calculation for example 2/4 = 0.5, except I can't find a data type that will store this value! Every time I make t开发者_C百科he calculation it says 0.

Anyone have any suggestions?


Either double or decimal will work fine.

However, if you just write:

// Wrong
double x = 2 / 4;

then it will still use integer division - because both of the operands for the division operator are of type int.

You can either cast either or both of the operands to double, or use a double literal for either or both of them:

// Any of these...
double x = (double) 2 / 4;
double x = 2 / (double) 4;
double x = (double) 2 / (double) 4;
double x = 2.0 / 4;
double x = 2 / 4.0;
double x = 2.0 / 4.0;
double x = 2d / 4;
double x = 2 / 4d;
double x = 2d / 4d;

Note that both double and decimal are floating point types. They don't represent arbitrary rational numbers (fractions). For example, neither can accurately represent 1/3. If you need a rational number type, you'll have to write your own or look for a third party implementation.


Make sure at least one of the divisor or the dividend is a floating number:

double d = 2 / 4.0;
Console.WriteLine(d): // Writes: 0.5


Use 2/4.0 to force it to use floating point arithmetics. Then you can store it in a double:

double d = 2/4.0;

If in the real code you have variables, cast the divisor to a double:

int i = 2;
int j = 4;
double d = i/(double)j;


You can cast,

double value = (double)2/4;

or you can provide your input with decimals

double value = 2.0/4.0;


Either float or double will do the job.

float x = 2f / 4f;
double x = 2d / 4d;

Note that you can specify constant values to be float or doubles by appending the appropriate character (f or d).

The important thing to remember is that the first data type (on the left) will determine the data type of the result. EDIT: actually, in this case either value being a float/double will work

So...

var x = 2 / 4;//x is int (0)
var x = 2f / 4;//x is float (0.5f)
var x 2d / 4;//x is double (0.5d)

C# will automatically convert int to float/double so...

float x = 2 / 4;//result type is int, but gets stored as convert float

Anyway, hope that helps explain some things

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜