0

Please help me understand (c#)

I’m trying to write some code for a very basic calculator. In my mind, it should work, but I keep getting an error saying I’m using the “answer” variable without assigning it a value. Wouldn’t the switch statement do that? I don’t get it :/ The code looks like this | | V using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { static void Main(string[] args) { //creates variables and sets values int num1 = Convert.ToInt32(Console.ReadLine()); string modifier = Console.ReadLine(); int num2 = Convert.ToInt32(Console.ReadLine()); int answer; //sets answer value switch(modifier){ case "+": answer = num1 + num2; break; case "-": answer = num1 - num2; break; case "*": answer = num1 * num2; break; case "/": answer = num1 / num2; break; } Console.WriteLine("{0} {1} {3} = {4}", num1, modifier, num2, answer); } } }

19th Oct 2019, 3:55 PM
Spencer Rich
Spencer Rich - avatar
3 Answers
+ 4
Spencer Rich , I made some corrections to your code. Hope it helps you đŸ˜ș https://code.sololearn.com/cVHp99fe9s57/?ref=app
19th Oct 2019, 4:31 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 2
whoops thank you
19th Oct 2019, 6:53 PM
Spencer Rich
Spencer Rich - avatar
+ 1
1. You need to initialize variable <answer> to zero. int answer = 0; 2. You are referring to an invalid index of parameter when you did this: Console.WriteLine("{0} {1} {3} = {4}", num1, modifier, num2, answer); It should've been Console.WriteLine("{0} {1} {2} = {3}", num1, modifier, num2, answer); <num1> → Index 0 <modifier> → Index 1 <num2> → Index 2 <answer> → Index 3 Hth, cmiiw
19th Oct 2019, 4:34 PM
Ipang