切换案例根据用户的选择调用函数

时间:2013-08-10 21:33:37

标签: c#

我有一个类似程序的计算器

如果用户输入1,他们可以添加,2减去,3减去乘,4分割

我得到了名为

的函数
         add
         subtract
         multiply
         divide

通过使用switch case,如果用户输入1,则必须转到add功能 2减去,3乘以和4除。

这是我得到的代码:

          static void Main()
          {         

                 Console.WriteLine("Enter any number");
                 int a = Convert.ToInt32(ConsoleReadLine());
                 Console.WriteLine("Enter any number");
                 int b = Convert.ToInt32(ConsoleReadLine());
                 int c;
                 Console.WriteLine("Enter 1 to add, 2 to subtract, 3 to multiply and 4 to divide");
                 int Choice = Convert.ToInt32(Console.ReadLine());
                 switch (Choice)
                   case 1:

                       break;
                     //and so forth.
                 public void add()
                 {
                       c = a + b;
                      // similar codes for subtraction,multiplication and division.
                 }

在切换情况下,如果用户输入1,则应调用add函数。 我该怎么做? 有什么建议。 它要求对象引用请帮助

3 个答案:

答案 0 :(得分:4)

你真的需要使用功能吗?这看起来很简单:

switch (Choice)
{
    case 1:
        c = a + b;
        break;
    ...
    default:
        Console.WriteLine("Invalid choice");
        break;
}

但是如果您确实想要使用函数,只需在Main方法之外定义它们(如果要从static调用它们,则必须将它们声明为Main):

public static int add(int x, int y)
{
    return x + y;
}

然后像这样调用它们:

switch (Choice)
{
    case 1:
        c = add(a, b);
        break;
    ...
    default:
        Console.WriteLine("Invalid choice");
        break;
}

答案 1 :(得分:1)

只需调用您的函数并返回结果:

static void Main()
{        
         Console.WriteLine("Enter any number");
         int a = Convert.ToInt32(ConsoleReadLine());
         Console.WriteLine("Enter any number");
         int b = Convert.ToInt32(ConsoleReadLine());
         int c;
         Console.WriteLine("Enter 1 to add, 2 to subtract, 3 to multiply and 4 to divide");
         int Choice = Convert.ToInt32(Console.ReadLine());
         switch (Choice)
           case 1:
                c = add(a,b);
               break;
             //and so forth.
}

public static int add(int a, int b)
{
    return a + b;
}

答案 2 :(得分:0)

你应该在switch case中调用add函数

switch (Choice)
               case 1:
                   add();
                   break;
                 //and so forth.
             public void add()
             {
                   c = a + b;
                  // similar codes for subtraction,multiplication and division.
             }