每日日報38——編寫程序,計算數組中奇數之和和偶數之和(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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM