标题:c#中普通数组和动态数组用法
只看楼主
龙魂少smile
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2017-9-4
 问题点数:0 回复次数:0 
c#中普通数组和动态数组用法
/*编写程序,计算数组中奇数之和和偶数之和。*/
//于博 20171010
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections; //头文件,包含Arraylist类型(c#中的动态数组)

namespace _20153236_sy1_4
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("*******欢迎进入计算一组数中奇(偶)数之和系统*******:");
            while (true)
            {
                Console.WriteLine("菜单:");
                Console.WriteLine("1.固定数量(10个)  2.不固定数量");
                Console.WriteLine("3.退出");
                Console.WriteLine("请选择:");
                int i; int Jsum = 0, Osum = 0;    //定义奇、偶总和
                i=int.Parse(Console.ReadLine());
                switch(i)
                {
                    case 1:                    //普通数组,固定数量,仅10个
                    int[] numarr = new int[10];   //定义数组
                     for (int j = 0; j < 10; j++) //for循环输入10个数
                    {
                       Console.WriteLine("请输入第{0}个数:", j + 1);
                      numarr[j] = int.Parse(Console.ReadLine());
                    }
                    for (int s = 0; s < 10; s++)  //计算数组中奇数之和和偶数之和
                    {
                        if(numarr[s]%2==0) Osum += numarr[s]; //判断数组中的值是偶数并累加
                        else Jsum += numarr[s];                //奇数累加
                    }
                    Console.WriteLine("奇数之和为" + Jsum + "\n偶数之和为" + Osum);break;
                    case 2:                          //动态数组,不固定个数
                    ArrayList numbers = new ArrayList(); int sum;
                    Console.WriteLine("请输入要输入的数的总个数:");
                    sum = int.Parse(Console.ReadLine());
                    for (int k = 0; k < sum; k++)
                    {
                        Console.WriteLine("请输入第{0}个数:", k+ 1);
                        numbers.Add(int.Parse(Console.ReadLine()));
                    }
                        for (int s = 0; s < sum; s++)
                    {
                        if ((int)numbers[s] % 2 == 0) Osum +=(int)numbers[s];//判断数组中的值是偶数并累加 (运算符%无法应用于object和int类型,需要强制转换)
                        else Jsum += (int)numbers[s];//奇数累加
                    }
                    Console.WriteLine("奇数之和为" + Jsum + "\n偶数之和为" + Osum);break;
                    case 3: Console.WriteLine("欢迎下次使用!!!"); break;
                    default: Console.WriteLine("输入错误!!!"); break;
                }//switch结束
                if (i == 3) break;         //跳出while循环
            }//while结束
        }
    }
}

搜索更多相关主题的帖子: 数组 之和 Console WriteLine int 
2017-10-10 20:13



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-481251-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.058621 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved