Please forgive my programming knowledge. I know this is a simple thing, but I do not understand why result is always 0. Why decimal will be fine?
int a = 100;
int b = 200;
decimal c = (a / b) * 100;
Many thanks.
Integers are whole numbers and their negative opposites. Therefore, these numbers can never be integers: fractions. decimals. percents.
To convert a decimal to a percentage, multiply by 100 (just move the decimal point 2 places to the right). For example, 0.065 = 6.5% and 3.75 = 375%. To find a percentage of a number, say 30% of 40, just multiply. For example, (30/100)(40) = 0.3 x 40 = 12.
so basically you can just do it like this: dogs = (population * percentage)/100; cats = (population - dogs); as dogs and population must to be Integers. Show activity on this post.
Integer division always truncates the remainder. This is done at the time that the number is divided, not when it's assigned to the variable (as I'm guessing you assumed).
decimal c = ((decimal)a / b) * 100;
The value a/b will return 0 always since they are integers. So when the values within the Brackets are evaluated you are technically doing this
decimal c = (0) * 100
Better do,
decimal c = ((decimal)a/(decimal)b) * 100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With