英文:
Swap two integers does not change value
问题
int a = 1;
int b = 7;
void SwapTwoIntegers(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
SwapTwoIntegers(a, b);
Console.WriteLine(a);
我尝试编写一个用于交换两个变量的函数,但似乎在我的代码中出了一些问题。
英文:
int a = 1;
int b = 7;
void SwapTwoIntegers(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
SwapTwoIntegers(a, b);
Console.WriteLine(a);
I was trying to write a function for swapping two variables, but it seems like i am going wrong somewhere in my code.
答案1
得分: 2
参数的默认方式是按值传递,这意味着你只修改了 a
和 b
的副本。
你需要按引用传递这些变量,这样才能修改原始值。
void SwapTwoIntegers(ref int a, ref int b)
参见 https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/method-parameters
英文:
The default for parameters is pass by value, which means you're only modifying a copy of a
and b
.
You'll want to pass the variables by reference, so that the originals can be modified.
void SwapTwoIntegers(ref int a, ref int b)
See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/method-parameters
答案2
得分: 0
这是因为您将a和b按值传递给SwapTwoIntegers方法,这意味着该方法接收原始变量的副本。在方法内部对a和b所做的任何更改只会影响副本,而不会影响原始变量。
要交换a和b的值,您可以修改SwapTwoIntegers方法以使用ref参数,像这样:
void SwapTwoIntegers(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
英文:
This is because you are passing a and b to the SwapTwoIntegers method by value, which means the method receives copies of the original variables. Any changes made to a and b inside the method only affect the copies, not the original variables.
To swap the values of a and b, you can modify the SwapTwoIntegers method to use ref parameters, like this:
void SwapTwoIntegers(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
答案3
得分: -1
你需要通过引用传递值,或者从SwapTwoIntegers函数中返回这些值,就像这样:
public (int, int) SwapTwoIntegers(int a, int b)
{
int temp = a;
a = b;
b = temp;
return (a, b);
}
(a, b) = SwapTwoIntegers(a, b);
我认为这是在C#中返回两个项目的方式,或者学习有关引用值的内容,https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref
希望能帮助到你。
英文:
you need to pass the values by reference, or either return the values from the SwapTwoIntegers function, something like
`public Tuple<int, int> SwapTwoIntegers(int a, int b)
{
int temp = a;
a = b;
b = temp;
return a, b;
}
a, b = SwapTwoIntegers(a, b);`
I think thats how you return two items in c#, or either learn about reference values https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref
Hope it helps
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论