C# 編寫程序,計算數組中奇數之和和偶數之和。


using System;
using System.Collections.Generic;

namespace Test_1_4
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> str = new List<string>();
            int len = 0;
            int oddsum = 0;
            int evensum = 0;
            Console.WriteLine("請輸入數組:");
            while (true)
            {
                string input = Console.ReadLine();
                if (input.Equals("") == false)//如果不是輸入為空則增加輸入記錄
                    str.Insert(len++, input);
                else
                    break;

            }
            string[][] every = new string[len][];//交叉數組,行固定,為上面得到的行數,每一行的長度不定(每行字符間以空格或其他分割)
            for(int i = 0; i < len; i++)
            {
                every[i] = str[i].Split();// C#對空格的分割方式之一
            }
            for(int i = 0; i < len; i++)
            {
                for(int j = 0; j < every[i].Length; j++)
                {
                    int aa;
                    aa = int.Parse(every[i][j]);
                    if ((aa % 2) == 1)
                    {
                        oddsum += aa;
                    }
                    else
                    {
                        evensum += aa;
                    }
                }
            }
            Console.WriteLine("奇數之和等於:");
            Console.WriteLine(oddsum);
            Console.WriteLine("偶數之和等於:");
            Console.WriteLine(evensum);
            Console.ReadKey();
        }
    }
}

截圖

 


免責聲明!

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



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