-1

This:

float a = 2 / 4; return a;

Will output as 0, while this:

float a = 2; float b = 4; float c = a / b; return c;

Will give a correct output 0.5.

Why am I getting this result?

  • Does [this](https://stackoverflow.com/questions/1205490/why-do-these-division-equations-result-in-zero) answer your question? – Sweeper May 30 '20 at 10:32

2 Answers2

0

Because 2 and 4 are the type of integer.

Type type1 = 2.GetType();
Type type2 = 4.GetType();
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
0

C# interprets 2 and 4 as plain integers, 2/4 is 0 using integer math (floor of 0.5).

Try using 2f and 4f instead to have floating point numbers. Refer to this documentation to see all possible number literals https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types#real-literals.

Code below works as expected:

public static void Main()
{
    float a = 2f / 4f;
    Console.WriteLine(a);
}