Struggling with reassigning a variable using a method in C# >< | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 1

Struggling with reassigning a variable using a method in C# ><

I'm struggling to figure out how to reassign "salaryBudget" as the increased value outside of the method, as this code returns the original input value for each outputs. As I understand it, the method call should be processed before the second output, but it seems to be doing nothing. Appreciate any guidance on this one! using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace soloLearn { class Program { 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(salaryBudget); Console.WriteLine("After the increase: " + salaryBudget); } //complete the method static void Increase(ref int salaryBudget, ref int percent) { int perc = (percent / 100) + 1; salaryBudget = salaryBudget * perc; } } }

7th Aug 2021, 2:56 PM
Evelyn
Evelyn - avatar
2 ответов
+ 6
You're actually very close, and in fact there's nothing wrong with your use of ref for passing by reference. The problem here is (percent / 100) + 1 always results in 1 if percent is <= 100, since the division of two ints result in an int value. Instead, divide by 100.0 and store perc as double, then cast the product of salaryBudget and perc back to int. static void Increase(ref int salaryBudget, ref int percent) { double perc = (percent / 100.0) + 1; salaryBudget = (int)(salaryBudget * perc); } This doesn't yield the most accurate results since we are getting a floored value at the end, but I believe the task requires salaryBudget to be int (?).
7th Aug 2021, 3:07 PM
Hatsy Rei
Hatsy Rei - avatar
+ 1
When you divide percent / 100 as integer then ie 5/100=0. But 5/100.0=0.05, why you should to code: static void Increase(ref int salaryBudget, ref int percent) { double perc = percent / 100.0 + 1; salaryBudget = Convert.ToInt32(salaryBudget * perc); }
7th Aug 2021, 3:16 PM
JaScript
JaScript - avatar