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

C#锯齿数组目标值查找:循环逻辑错误修复求助

修复锯齿数组中目标值判断的逻辑错误

问题根源

你的代码里根本没有调用自己写的target查找方法,而是错误地用Convert.ToBoolean(targetValue)把输入的整数转成布尔值——在C#里,只要整数不是0,Convert.ToBoolean就会返回true,只有0才返回false,这就是为什么无论目标值是否在数组里,输出结果都不符合预期。

修复步骤

  1. 删除错误的bool answer = Convert.ToBoolean(targetValue);语句
  2. 替换为调用你定义的查找方法,传入锯齿数组和目标值
  3. (可选)按照C#命名规范,将方法名target改为大写开头的TargetExists,提升代码可读性

修复后的完整代码

class HW03_04
{
    static void Main()
    {
        int[][] array =
        {
            new int[] {9, 6, 48, 15, 23},
            new int[] {7, 56, 23, 4, 62},
            new int[] {13, 25, 7, 56, 2},
            new int[] {84, 30, 5, 0, 17}
        };
        Console.Write("What is your target value? ");
        int targetValue = Convert.ToInt32(Console.ReadLine());
        // 调用查找方法,替换之前错误的布尔值转换
        bool answer = TargetExists(array, targetValue);
        Console.WriteLine("{0}", answer);
    }
    // 修正方法名符合C#规范,原循环逻辑本身正确
    static bool TargetExists(int[][] arrSearch, int targetValue)
    {
        int size = arrSearch.Length;
        for (int i = 0; i < size; i++)
        {
            for (int j = 0; j < arrSearch[i].Length; j++)
            {
                if (arrSearch[i][j] == targetValue)
                {
                    return true;
                }
            }
        }
        return false;
    }
}

额外说明

你写的双层循环查找逻辑本身是正确的:遍历锯齿数组的每一个子数组,再遍历子数组中的每个元素,找到目标值就立即返回true,遍历完所有元素都没找到就返回false。问题完全出在Main方法里没有正确调用这个查找方法,而是用了错误的布尔值转换逻辑。

内容的提问来源于stack exchange,提问作者Wonjun Seo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:15:24