Answer the question
In order to leave comments, you need to log in
How to correctly assign a local value to a variable in C#?
Good evening!
I am writing my second curriculum in C# - a console calculator.
The goal is this:
using System;
namespace csharp_dotnetcore_calculator
{
class Program
{
public static float add(float first,float second)
{
return first + second;//Сложение
}
public static float subtraction(float first,float second)
{
return first - second;//Вычитание
}
public static float multiplication(float first,float second)
{
return first * second;
}
public static float division(float first,float second)
{
return first / second;
}
static void Main(string[] args)
{
Console.WriteLine("Добро пожаловать в калькулятор!");
while (true)
{
Console.WriteLine("Введите первое число:");
float f = float.Parse(Console.ReadLine());
Console.WriteLine("Введите операнд(+,-,*,/):");
string o = Console.ReadLine();
Console.WriteLine("Введите второе число:");
float s = float.Parse(Console.ReadLine());
float result;
if (o == "+")
{
result = add(f, s);
}
else if(o == "-")
{
result = subtraction(f, s);
}
else if(o == "*")
{
result = multiplication(f, s);
}
else if(o == "/")
{
result = division(f, s);
}
string value = $"Результат: {result}";
Console.WriteLine(value);
}
}
}
}
Answer the question
In order to leave comments, you need to log in
float result;
If the user enters something other than { +, -, *, / } as an operation, undefined behavior will result. result will not be initialized at the moment
Either do
Or (which is more correct) - do not allow the possibility of such a situation at all
string value = $"Результат: {result}";
float result = 0f;
if (o == "+")
{
result = add(f, s);
}
else if(o == "-")
{
result = subtraction(f, s);
}
else if(o == "*")
{
result = multiplication(f, s);
}
else if(o == "/")
{
result = division(f, s);
}
else
throw new Exception($"Unexpected operation '{o}'");
Do as in the calculator the first variable is the result of the second and third operations and the entered value.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question