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?
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?
Because 2 and 4 are the type of integer.
Type type1 = 2.GetType();
Type type2 = 4.GetType();
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);
}