用 C# 构建简单的计算器
Building simple calculator with C#
我正在尝试在 C# 上构建一个非常简单的计算器,我想将结果存储在变量“result”中并通过 Console.WriteLine(result) 显示它。出于某种原因 Console.WriteLine(result) 是不允许的。
using System;
namespace Giraffe
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("insert number1");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("insert operator");
string op = Console.ReadLine();
Console.WriteLine("insert number2");
double num2 = Convert.ToDouble(Console.ReadLine());
if (op == "+")
{
double result = num1 + num2;
}
else if(op == "-")
{
double result = num1 - num2;
}
else if (op == "*")
{
double result = num1 * num2;
}
else if (op == "/")
{
double result = num1 / num2;
}
Console.WriteLine(result);
}
}
}
非常感谢
在 if
语句外声明 double result
static void Main(string[] args)
{
Console.WriteLine("insert number1");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("insert operator");
string op = Console.ReadLine();
Console.WriteLine("insert number2");
double num2 = Convert.ToDouble(Console.ReadLine());
double result = 0;
if (op == "+")
result = num1 + num2;
else if (op == "-")
result = num1 - num2;
else if (op == "*")
result = num1 * num2;
else if (op == "/")
result = num1 / num2;
Console.WriteLine(result);
}
我正在尝试在 C# 上构建一个非常简单的计算器,我想将结果存储在变量“result”中并通过 Console.WriteLine(result) 显示它。出于某种原因 Console.WriteLine(result) 是不允许的。
using System;
namespace Giraffe
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("insert number1");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("insert operator");
string op = Console.ReadLine();
Console.WriteLine("insert number2");
double num2 = Convert.ToDouble(Console.ReadLine());
if (op == "+")
{
double result = num1 + num2;
}
else if(op == "-")
{
double result = num1 - num2;
}
else if (op == "*")
{
double result = num1 * num2;
}
else if (op == "/")
{
double result = num1 / num2;
}
Console.WriteLine(result);
}
}
}
非常感谢
在 if
语句外声明 double result
static void Main(string[] args)
{
Console.WriteLine("insert number1");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("insert operator");
string op = Console.ReadLine();
Console.WriteLine("insert number2");
double num2 = Convert.ToDouble(Console.ReadLine());
double result = 0;
if (op == "+")
result = num1 + num2;
else if (op == "-")
result = num1 - num2;
else if (op == "*")
result = num1 * num2;
else if (op == "/")
result = num1 / num2;
Console.WriteLine(result);
}