返回顶部

一缕半夏微光

温柔半两,从容一生

导航

编写程序,计算数组中奇数之和和偶数之和(C#)

一、效果如下:

二、代码如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Test4
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             int[] array;
14             int j=0, o=0;//j代表基数和,o代表偶数和
15             Console.WriteLine("请输入数组的长度:");
16             int length = Convert.ToInt32(Console.ReadLine());
17             array = new int[length];
18             for (int i = 0; i < length; i++)
19             {
20                 Console.Write("请输入第{0}个数组的值:", i);
21                 array[i] = Convert.ToInt32(Console.ReadLine());
22             }
23             Array.Sort(array);//排序,从小到大
24 
25             foreach (int i in array)
26             {
27                 if (i % 2 == 0)
28                 {
29                     o += i;
30                 }
31                 else
32                 {
33                     j += i;
34                 }
35             }
36             Console.WriteLine("奇数之和为:{0}",j);
37             Console.WriteLine("偶数之和为:{0}",o);
38             Console.ReadKey();
39         }
40     }
41 }

参考链接:

https://www.imooc.com/wenda/detail/529324

posted on 2021-10-14 20:43  一缕半夏微光  阅读(850)  评论(0编辑  收藏  举报