C++代码札记(六)实现近似值算法

来源:互联网 发布:进销存着淘宝 编辑:程序博客网 时间:2024/05/20 06:40


/*就比如数字是5,那么如果输入数组{1,2,3}就显示出2和3            如果数字是11,那么{6,12,1,2}就显示6,1,2            要求使用递归,实在设计不出这个算法*/

            Func<int[], List<int>> 组合和 = delegate(int[] 数组)            {                List<int> 组和 = new List<int>();                foreach (int 幕 in Enumerable.Range(1, Convert.ToInt32(Math.Pow((double)2, (double)数组.Length)) - 1))                {                    int 商 = 幕, 和 = 0;                    foreach (int 位 in Enumerable.Range(0, 数组.Length))                    {                        和 += 商 % 2 == 0 ? 0 : 数组[位];                        商 /= 2;                        if (商 == 0) break;                    }                    组和.Add(和);                }                return 组和.Except(数组).ToList();            };            var 和组 = 组合和(new int[] { 2, 3, 6, 9 });            Console.WriteLine("13 小近{0} 大近{1}", 和组.FindAll(组 => 组 <= 13).Max(), 和组.FindAll(组 => 组 >= 13).Min());

非递归算法如上.

圆周率近似值π=4-4/3+4/5-4/7+4/9……,回答程序要计算多少项才能得到数值3.14 3.141 3.1415

        Dim 累积 As Double = 4, 次数 As Int16 = 1        Dim 控制 = {False, False, False}        For Each 序 In Enumerable.Range(1, 10000).Select(Function(x) x * 2 + 1)            If 次数 Mod 2 = 0 Then 累积 += 4 / 序 Else 累积 -= 4 / 序            次数 += 1            If 控制(0) = False Then                If Math.Round(累积, 2) = 3.14 Then                    Console.WriteLine("{0}次 {1}", 次数.ToString("000"), Math.Round(累积, 2))                    控制(0) = True                End If            End If            If 控制(1) = False Then                If Math.Round(累积, 3) = 3.141 Then                    Console.WriteLine("{0}次 {1}", 次数.ToString("000"), Math.Round(累积, 3))                    控制(1) = True                End If            End If            If 控制(2) = False Then                If Math.Round(累积, 4) = 3.1415 Then                    Console.WriteLine("{0}次 {1}", 次数.ToString("000"), Math.Round(累积, 4))                    控制(2) = True                End If            End If            'Exit For        Next




0 0
原创粉丝点击