[英]While Loop in C#
I want to exit from loop when both i and j have the value 6. but it exits when and one of them have value 6.当 i 和 j 的值为 6 时,我想退出循环。但是当其中一个值为 6 时它退出。
int i,j,k;
i=k=0;
j=1;
Random num = new Random();
Console.WriteLine("Please Press any Key to Roll");
while((i!=6)&&(j!=6))
{
Console.ReadKey();
i= num.Next(0,7);
j= num.Next(0,7);
Console.WriteLine("1st Rolled Number is: "+ i);
Console.WriteLine("2st Rolled Number is: "+ j);
k++;
}
Console.WriteLine("Your have achieved it in "+ k + " Atempts");
To exit the loop when both i and j have the value 6, you can change the condition in the while loop to要在 i 和 j 的值都为 6 时退出循环,可以将 while 循环中的条件更改为
Change too也改变
while ((i != 6) || (j != 6))
This will exit the loop when either i or j.这将在 i 或 j 时退出循环。 To exit the loop when both i and j have the value 6,当 i 和 j 的值为 6 时退出循环,
while (!(i == 6 && j == 6))
This will exit the loop when both i and j have the value 6.当 i 和 j 的值为 6 时,这将退出循环。
In other words, the loop should continue if either i
isn't 6 or j
isn't 6 - this is a logical or ( ||
) condition, not a logical and ( &&
) condition:换句话说,如果i
不是 6 或j
不是 6,则循环应该继续 - 这是逻辑或 ( ||
) 条件,而不是逻辑与 ( &&
) 条件:
while ((i != 6) || (j != 6))
an alternative approach can be另一种方法可以是
while(true)
{
Console.ReadKey();
i = num.Next(0, 7);
j = num.Next(0, 7);
Console.WriteLine("1st Rolled Number is: " + i);
Console.WriteLine("2st Rolled Number is: " + j);
k++;
if (i == 6 && j == 6) break;
}
Console.WriteLine("You have achieved it in " + k + " attempts");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.