Function CarbonEquivalentFactor below contained a bug where the result was rounded to the nearest integer, instead of a decimal value of double type.
public double CarbonEquivalentFactor(int fromNoCarbonAtoms, int toNoCarbonAtoms)
{
return fromNoCarbonAtoms / toNoCarbonAtoms;
}
Adding a type cast to one of the variables works and the function returns a correct decimal value as a double
public double CarbonEquivalentFactor(int fromNoCarbonAtoms, int toNoCarbonAtoms)
{
return (double)fromNoCarbonAtoms / toNoCarbonAtoms;
}
It seems logical that it would be correct to add a type cast to both operands, like below:
public double CarbonEquivalentFactor(int fromNoCarbonAtoms, int toNoCarbonAtoms)
{
return (double)fromNoCarbonAtoms / (double)toNoCarbonAtoms;
}
However then Visual Studio gives me the IDE0004 hint, "Remove unnecessary cast". Compiling and executing the function with both type casts also re-introduces the same bug i.e. the result is rounded to nearest integer.
Why is this so?
The project is in .NET standard 2.0. I'm using MS Test framework 2.1.1 in a .NET Core 3.1 project to unit test the function.
[DataTestMethod]
[DataRow(5, 1)]
[DataRow(3, 1)]
[DataRow(1, 3)]
[DataRow(0, 1)]
[DataRow(2, -1)]
[DataRow(-2, -2)]
[DataRow(3242424, 9343243)]
public void CarbonEquivalentFactorTest(int from, int to)
{
var result = Emission.CarbonEquivalentFactor(from, to);
var resultNET= emissionsNET.CarbonEquivalentFactor(from, to);
Assert.AreEqual(result, resultNET);
}
The Emission class is a COM object in C++ and the other emissionsNET is .NET class ported to C#. The .NET function returns 0 when parameters are 1 and 3. And when having double type cast on both operands in division as below:
public double CarbonEquivalentFactor(int fromNoCarbonAtoms, int toNoCarbonAtoms)
{
return (double)fromNoCarbonAtoms / (double)toNoCarbonAtoms;
}
UPDATE It must have been something with my setup or some glitch in Visual Studio. Now I can't reproduce the above bug, and the function returns 0.3333 when in parameters are 1 and 3. Anyway thanks for the time and help! I have at least sharpened my C# skills a bit today.