You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# While循环问题:需i和j均为6时退出却提前退出

问题修正方案

原代码的循环条件逻辑错误,导致只要其中一个变量为6就提前退出循环。要实现当i和j同时为6时才终止循环,需要调整循环的判断条件:

错误原因

原条件(i!=6)&&(j!=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");
// 循环条件改为:只要i和j不同时为6,就继续循环
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("2nd Rolled Number is: " + j); // 修正原代码拼写错误:2st → 2nd
    k++;
}
Console.WriteLine("You have achieved it in " + k + " Attempts"); // 修正原代码拼写错误:Your → You,Atempts → Attempts

补充说明

  • 修正后的循环条件!(i == 6 && j == 6)等价于i != 6 || j != 6,两种写法均可,前者更直观表达“不同时为6就继续循环”的逻辑。
  • 顺带修正了代码中的几处拼写错误,避免输出文本出现语法问题。

内容的提问来源于stack exchange,提问作者Ahsan Ali Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 06:30:36