-4

我试图让该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

4 回答 4

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;
}

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

编辑

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

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

    int temp;
    temp = first;
    first = last;
    last = temp;
}
于 2013-09-03T05:09:10.623 回答
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;
    }
于 2013-09-03T05:11:00.083 回答
1

first你在and 和firstIntlast之间搞混了lastInt

private static void Swap(ref int first, ref int middle, ref int last){
 int temp = first;
 first = last;
 last = temp;
}
于 2013-09-03T05:08:49.467 回答
0

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

private static void Swap(ref int first, ref int middle, ref int last) {
    first ^= last;
    last ^= first;
    first ^= last;
}
于 2013-09-03T05:21:22.610 回答