Home > Enterprise >  C# Mathemathics
C# Mathemathics

Time:09-22

I wanted to ask a question about a calculation I had today in C#.

double expenses = (pricePen   priceMark   priceLitres) - discount / 100*(pricePen   priceMark   priceLitres); //Incorrect

double expenses = (pricePen   priceMark   priceLitres) - (pricePen   priceMark   priceLitres)* discount/100;   //Correct 

So as you can see at the end of the equation I had to multiply the brackets by the integer named "discount", which is obviously a discount percentage.

When I change the places of that value whether it would be in front of the brackets or behind the brackets the answer will always be different, but in Maths I even checked myself that I should get the same answer even if the value is placed in front of the brackets to multiply or placed behind the brackets to multiply again, but C# doesn't think so.

I wanted to ask people, how does C# actually calculate this and why am I getting different results at the end? (Result should be 28.5, not 38)

[Data: pricePen = 11.6; priceMark = 21.6;  priceLitres = 4.8; discount = 25;]

(I know that the question is irrelevant.)

CodePudding user response:

In first line after dividing by 100 the result is in an integer. For that the rest of division get lost. So the multiplication has a lower result.
In second line the multiplication has the correct result and the rest of devision is lower than one.

CodePudding user response:

So I know its already answered but if you want to learn more about divisions with int here it is:

for example:

float value = 3/4 you would expect it to be 0.75 but that's not the case.

Because when the Compiler goes through the values 3 and 4 he makes des Literal of the highest data type - in this case (int)-. That means the result of this division will be "0".75 because int has no floating numbers and just cuts it off. Then the program just takes that value and puts it in the float value ... so the result will be

"3/4" 0 ->"float value" 0.0 = 0.0

Some guys before me already told you the solution to that problem like making one divisor to float with .0

float value = 3.0/4

or you can tell the Compiler to store the value in a float Literal with the (float) "command"

float value = (float) 3/4

I hope it helped you explain why you did that :)

CodePudding user response:

To avoid these problems makes sure you are doing math with floating point types, and not int types. In your case discount is an int and thus

x * (discount / 100) = x * <integer>

Best to define a function to do the calculation which forces the type

double DiscountedPrice(double price, double discount)
{
    return price - (discount/100) * price;
}

and then call it as

var x = DiscountedPrice( pricePen   priceMark   priceLitres, 15);

In the above scenario, the compiler will force the integer 15 to be converted into an double as a widening conversion (double has more digits than integer).

  • Related