交换firstInt,middleInt和lastInt时出现问题

时间:2013-09-03 05:02:01

标签: c#

我试图让Main()方法声明三个名为firstInt,middleInt和lastInt的整数。并将这些值分配给变量,显示它们,然后将它们传递给接受它们作为引用变量的方法,将第一个值放在lastInt变量中,并将最后一个值放在firstInt变量中。在Main()方法中,再次显示三个变量,证明其位置已被反转。

static void Main(string[] args)
{

    int first = 33;
    int middle = 44;
    int last = 55;

    Console.WriteLine("Before the swap the first number is {0}", first);
    Console.WriteLine("Before the swap the middle number is {0}", middle);
    Console.WriteLine("Before the swap the last number is {0}", last);

    Swap(ref first, ref middle, ref last);
    Console.WriteLine("\n============AFTER===THE===SWAP======================");
    Console.WriteLine("After the swap the first is {0}", first);
    Console.WriteLine("After the swap the middle is {0}", middle);
    Console.WriteLine("After the swap the last is {0}", last);
}

private static void Swap(ref int first, ref int middle, ref int last);

   int temp;
    temp = firstInt;
    firstInt = lastInt;
    lastInt = temp;

   }
}

4 个答案:

答案 0 :(得分:3)

这是问题所在:

private static void Swap(ref int first, ref int middle, ref int last);

   int temp;
    temp = firstInt;
    firstInt = lastInt;
    lastInt = temp;

   }

您的方法;的参数列表后面有一个Swap,它应该是{(大括号):

private static void Swap(ref int first, ref int middle, ref int last)
{

    int temp;
    temp = firstInt;
    firstInt = lastInt;
    lastInt = temp;
}

您的代码会生成“类型或命名空间定义,或期望的文件结尾”。错误。

修改

正如其他人所指出的那样,你也有错误的变量名称 - 它应该是firstmiddlelast,所以你的整个方法应该是:

private static void Swap(ref int first, ref int middle, ref int last)
{

    int temp;
    temp = first;
    first = last;
    last = temp;
}

答案 1 :(得分:1)

您在firstfirstIntlastlastInt之间混淆了:

private static void Swap(ref int first, ref int middle, ref int last){
 int temp = first;
 first = last;
 last = temp;
}

答案 2 :(得分:1)

不确定我为什么回答,但这都是简单的编译问题

   private static void Swap(ref int first, ref int middle, ref int last); <-- semicolon should not be here
      <-- missing bracket
       int temp;
        temp = firstInt; <-- none of these names exist
        firstInt = lastInt;
        lastInt = temp;

    }

应该是:

    private void Swap(ref int first, ref int middle, ref int last)
    {
        int temp;
        temp = first;
        first = last;
        last = temp;
    }

答案 3 :(得分:0)

或者有一些XOR交换优点(没有临时变量):

private static void Swap(ref int first, ref int middle, ref int last) {
    first ^= last;
    last ^= first;
    first ^= last;
}