Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't I assign 1.2 value to float variable in C#? I did the same in C and C++, and it worked

why can't I assign 1.2 value to float variable in C#? I did the same in C and C++, and it worked.

class Program
{
    private readonly int a = 20;
    private readonly float b;      

    public Program(float tmp)
    {
        b = tmp;
    }
    static void Main(string[] args)
    {
        Program obj1 = new Program(1.2);
        Console.Read();
    }
}

It gives error can not convet double to float. Why is so isn't 1.2 float value?

like image 864
Mohan Mahajan Avatar asked Jul 17 '11 04:07

Mohan Mahajan


People also ask

Is 1.1 a float or double?

1.1 is not a binary float The leading '1' converts straight across, and to generate subsequent binary digits we just repeatedly multiply by two.

Is 1.5 float or double?

And the reason the comparison succeeds with 1.5 is that 1.5 can be represented exactly as a float and as a double ; it has a bunch of zeros in its low bits, so when the promotion adds zeros the result is the same as the double representation.

How many decimals is a float in C?

float has 7 decimal digits of precision. double is a 64-bit IEEE 754 double precision Floating Point Number – 1 bit for the sign, 11 bits for the exponent, and 52* bits for the value. double has 15 decimal digits of precision.

Can we assign integer value to float in C?

Yes, an integral value can be added to a float value. The basic math operations ( + , - , * , / ), when given an operand of type float and int , the int is converted to float first. So 15.0f + 2 will convert 2 to float (i.e. to 2.0f ) and the result is 17.0f .


2 Answers

1.2 is a double (8 bytes).
1.2f is a float (4 bytes).

More details

like image 56
SLaks Avatar answered Oct 11 '22 07:10

SLaks


Any literal number in your code which includes a decimal point is interpreted as a double, not a float, unless you mark it as a float by appending f.

Doubles are not automatically converted to floats, since this can result in a loss of precision.

To fix your code, you can either:

  • mark your literal number as a float:

    Program obj1 = new Program(1.2f);

  • or, explicitly cast it as a float:

    Program obj1 = new Program((float)1.2);

The former option should be preferred when using a numeric literal, but if you are passing a variable typed as a double, then you can use the latter one.

like image 29
Ergwun Avatar answered Oct 11 '22 07:10

Ergwun