将一个较小的数字除以一个较大的数字在没有特殊 declecation c# 的情况下不起作用

Dividing one smaller number with the bigger one doesn't work without special decleration c#

这个:

float a = 2 / 4; return a;

将输出为 0,而此:

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

将给出正确的输出 0.5。

为什么我会得到这个结果?

因为2和4是整型

Type type1 = 2.GetType();
Type type2 = 4.GetType();

C# 将 2 和 4 解释为普通整数,2/4 是 0 使用整数数学(0.5 的下限)。

尝试使用 2f4f 代替浮点数。请参阅此文档以查看所有可能的数字文字 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types#real-literals.

下面的代码按预期工作:

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