我目前正在尝试获得一个每次运行时增加1的数字,我使用的是while循环,所以理论上每次循环都在下面的代码中运行时,int i应该返回1,2, 3,4等等虽然它返回1,1,1,1,1。只是无法理解这一点。
public static void getresponse(ref int i)
{
i++;
System.Console.WriteLine(i);
}
答案 0 :(得分:3)
每次循环运行时,您重新声明i并将其设置为0.
将int i = 0
移到while循环之外。
int i = 0;
while (true)
{
getresponse(ref i);
}
答案 1 :(得分:1)
在while循环之外声明我。每次都设置为0.
static void Main(string[] args)
{
int i = 0;
while (true)
{
getresponse(ref i);
}
}
public static void getresponse(ref int i)
{
i++;
System.Console.WriteLine(i);
}
答案 2 :(得分:0)
您是否注意到在每次迭代时将i重置为0?
只需在while块之外声明我就可以了。
答案 3 :(得分:0)
将你的计数器放在循环之外。
static void Main(string[] args)
{
int i = 0;
while (true)
{
getresponse(ref i);
}
}
public static void getresponse(ref int i)
{
i++;
System.Console.WriteLine(i);
}