-1

I'm a total beginner. I've just made a small C# program on SharpDevelop that simply calculates the square root of the first few integers. Here it is:

public static void Main(string[] args)
    {

        int i;

        XXXXX[] t = new XXXXX[40];

        for(i=0; i<t.Length; i++)
        {
            t[i]=Math.Sqrt(i);
        }

        for(i=0; i<t.Length; i++)
        {
            Console.WriteLine(""+t[i]);
        }

        Console.ReadKey(true);
    }

My question is:

Why does my program work when I write "double" instead of the "XXXXX" but doesn't work when I write "float" instead of the "XXXXX" ?

I thought I heard my teacher say that float and double are similar, except that double has more precision. So I don't understand why I can't use float instead of double...

user50746
  • 281
  • 2
  • 4
  • 10

4 Answers4

6

Math.Sqrt() returns a double so when you try to assign it to a float, you get a compilation error. This is because float has less precision than double so you may potentially lose detail.

See the documentation for float and double.

You could explicitly convert the number:

t[i]=(float)Math.Sqrt(i);
DavidG
  • 113,891
  • 12
  • 217
  • 223
2

Simply because Math.Sqrt returns a double.

Cast to float if needed (but you'll indeed lose precision):

t[i]=(float)Math.Sqrt(i);
xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
1

You have to convert the result of Math.Sqrt(i) explicit to a float:

t[i] = (float)Math.Sqrt(i);
Oliver
  • 43,366
  • 8
  • 94
  • 151
0

Think of a float as a small box (actually an amount of memory), then think of a double as a large box (also an amount of memory). Now consider that Math.Sqrt gives you (returns) a big thing (actually a number) to put in a box. If you use a double (big box) the thing that you're given fits in nicely. If you use float (the small box) then the thing wont fit and you'll need to cut some bits off (lose precision) to squish it in the box!

Luke Baughan
  • 4,658
  • 3
  • 31
  • 54