A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 李晓泉 中级黑马   /  2013-3-13 19:51  /  1150 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

一个数组里的奇数读出来放到另一个数组里返回,main函数里调用返回的值输出,怎么重新弄一个数组,况且新数组长度不确定

4 个回复

倒序浏览
可以使用arry数组,动态数组,动态增长
回复 使用道具 举报
如果数组长度不确定,建议用泛型集合,下面是实现的代码:
     /// <summary>
        /// 如果数组长度不一定,建议用List
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            int[] strNew = GetOdd(nums);
            foreach (var item in strNew)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();

        }

        public static int[] GetOdd(int[] nums)        
        {
            List<int> oddList = new List<int>();//创建List存储不定长度的数组
            for (int i = 0; i < nums.Length; i++)
            {
                if (nums[i] % 2 != 0)
                {
                    oddList.Add(nums[i]);
                }
            }
            int[] numsNew = oddList.ToArray();
            return numsNew;
        }

评分

参与人数 1技术分 +1 收起 理由
彭清贵 + 1

查看全部评分

回复 使用道具 举报
方法中用数组可以使用parmas修饰 表示可变数组
回复 使用道具 举报
不用泛型来解决 变向确定数组的个数 不知意下何如
            int[] arr = { 1, 2, 5, 4, 8, 9, 44 };
            int n = 0;
            //确定数组的个数
            foreach (int i in arr)
            {
                if (i % 2 != 0)
                {
                    n++;
                }
            }
            //放奇数的数组
            int[] arr2 = new int[n];
            int m = 0;
            foreach (int j in arr)
            {
                if (j % 2 != 0)
                {
                    arr2[m] = j;
                    m++;
                }
            }
            foreach (int t in arr2)
            {
                Console.WriteLine(t);
            }
            Console.ReadKey();

评分

参与人数 1技术分 +1 收起 理由
彭清贵 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马