Pregunta

I've got this line of code:

int WStoneCost = PriceMethod.StoneCost / 100 * AP;

While PriceMethod.StoneCost is equal to 25 and AP is equal to 70. I've checked it using breakpoints and I can't understand why do I get zero after I run this line. (WStoneCost is equal to zero) Is it just a wrong symbol or am I doing something wrong? Thanks in advance. And how to get a correct double at the end? Like 17.5

¿Fue útil?

Solución

You are doing integer division, so 25/100 is 0, not 0.25, and hence 0 * 70 is 0. Since your result variable is also an int it's unclear what result you are expecting, but you could reorder the operations to get a non-zero answer:

int WStoneCost = (PriceMethod.StoneCost * AP)/ 100 ;

It's still integer division, but with your inputs will divide 25*70 (1,750) by 100, which will give you 17.

If you want a floating-point decimal result, just use 100m:

decimal WStoneCost = (PriceMethod.StoneCost * AP)/ 100m ;

Since the literal 100m is a decimal, then the compiler will use floating-point decimal division, which will give you a decimal result.

Otros consejos

And how to get a correct double at the end? Like 17.5

Your question and both of the two answers given so far indicate that all three of you want to do something dangerously wrong. You are doing financial calculations so you should always be using decimal, never double. double is for physics calculations, not financial calculations.

I agree with JonathanWood. According to the values that you provided, your answer is going to produce a fractional number. Therefore, you need WStoneCost to be a double or a float. Also, you might want to use partentheses in your equations to ensure that the order of operations is carried out to your expectations.

Hope this helps!

-Gary The Bard

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top