【发布时间】:2016-08-14 14:15:38
【问题描述】:
我正在用一个非常基本的计算器脚本练习 switch 语句,但我很困惑为什么我写出浮点变量 result 的最后一行收到错误:“使用未分配的局部变量”。是的,有很多更好的方法可以制作一个涉及循环的计算器,接下来我想尝试一下,但现在它是 C# 的小步骤。下面是我的代码,谢谢大家!
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
// Greeting.
Console.WriteLine ("Welcome to the basic calculator");
// Get first value.
Console.WriteLine ("Enter the first value.");
string firstValueAsText = Console.ReadLine ();
float a = Convert.ToSingle (firstValueAsText);
// Get second value.
Console.WriteLine ("Enter the second value.");
string secondValueAsText = Console.ReadLine ();
float b = Convert.ToSingle (secondValueAsText);
// Prompt operation.
Console.WriteLine ("Enter '+', '-', '*', '/', '^'.");
string operation = Console.ReadLine ();
// Establishing the result and error variables for later.
float result;
string error = "ERROR";
// Define switch operations.
switch (operation)
{
case "+":
result = a + b;
break;
case "-":
result = a - b;
break;
case "*":
result = a * b;
break;
case "/":
result = a / b;
break;
case "^":
result = (float)Math.Pow(a, b);
break;
default:
Console.WriteLine (error);
break;
}
// Print the result.
Console.WriteLine (a + " " + operation + " " + b + " = " + result);
Console.ReadKey ();
}
}
}
【问题讨论】:
-
看看如果用户输入了一个无效的操作会发生什么。
标签: c# .net asp.net-mvc