0

How to use an integer as a percentage in C# (Without using doubles)

How do I use an int variable as a percentage, to calculate data. For example, I'm doing a practice for "Passing Arguments" in C# and I need to read in two integers, a salary and a raise. For example 5000 & 15. Im supposed to figured out the total salary after 5000 has been increased by 15% Here's my code but I don't understand why the math is correct on paper, yet not in the computer. static void Main(string[] args) { int salaryBudget = Convert.ToInt32(Console.ReadLine()); int percent = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Before the increase: " + salaryBudget); //complete the method call Increase(ref salaryBudget, ref percent); Console.WriteLine("After the increase: " + salaryBudget); } //complete the method static void Increase(ref int a, ref int b) { a = (a + (a * (b/100))) }

14th Jun 2021, 3:34 AM
Doriiion
Doriiion - avatar
2 Respostas
+ 3
Because `b / 100` (which yields 0) is wrapped in parentheses, it is calculated first before it is multiplied by <a>. So ( a * ( b / 100 ) ) is evaluated as ( a * ( 0 ) ) because integer division reserves no fraction part. And it wraps up into a = ( a + ( a * ( 0 ) ) ) which equals a = ( a + ( 0 ) ) And there's the reason. Remove the parentheses around b / 100 and it'll be fine. a = ( a + ( a * b / 100 ) ); // <- like this P.S. I don't think <b> needs to be passed by reference, it is not being modified in the `Increase` function.
14th Jun 2021, 5:20 AM
Ipang
+ 1
Ipang much appreciation!
14th Jun 2021, 7:17 PM
Doriiion
Doriiion - avatar