初学C#必须要掌握的基础例题

目录

1. 长方形形式的九九乘法表

​编辑

2. 下三角形式的九九乘法表

3.水仙花数

4.输入数的正逆之和

5. 闰年、月份的判断

6.比较大小

7.冒泡排序

8.数组元素的调换

9.数组元素的输入输出 

10.面向对象


1. 长方形形式的九九乘法表

         通过观察外部循环加1,内部循环从1,逐步加1到9;所以会用到两次for循环,程序如下:

for (int i = 1; i <= 9; i++)                    //外部循环 ,从1开始到9  
    {
            for (int j = 1; j <= 9; j++)            //外部循环加1(i++),内部循环从1到9
            {
             Console.Write("{0}*{1}={2}\t", i, j, i * j);            // \t是转义字符,相当于执行一次Tab键空四个格
            }
            Console.WriteLine();           //内部循环9次,执行一次Console.WriteLine();即换行
    }

        其中 Console.Write();与Console.WriteLine();区别是前者连续输出,后者换行输出。
输入完代码后,在Visual Studio的菜单栏中点击生成-->生成解决方案,或者F6快捷键编译代码,在Visual Studio的菜单栏中点击调试-->开始调试,或者F5执行代码。

2. 下三角形式的九九乘法表

 九九乘法表的输出形式分为长方形形式和下三角形式,通过观察发现当内部循环数与外部循环数不同时,执行连续空格输出,当内部循环数与外部循环数相同时,执行换行输出,所以要用到 if 判断语句判断内部循环数与外部循环数是否相等,程序如下:

for (int i = 1; i <= 9; i++)        //外部循环从 1 到 9
    {
        for (int j = 1; j <= i; j++)        //内部循环从 1 到 i,到等于i
        {
            if (i == j)                //判断当内部循环与外部循环的值相等的情况下,要执行的代码
            {
                Console.WriteLine("{0}*{1}={2}", i, j, i * j);        //Console.WriteLine();换行输出,{0},{1},{2}为C#中的占位符。相当于C语言中的%d,%c,%f 等。
            }
            else            // if 语句不成立的即:当内部循环与外部循环的值不等的情况下
            {
                Console.Write("{0}*{1}={2}\t", i, j, i * j);        //Console.Write();不换行输出
            }
        }
    }

输入完代码后,在Visual Studio的菜单栏中点击生成-->生成解决方案,或者F6快捷键编译代码,在Visual Studio的菜单栏中点击调试-->开始调试,或者F5执行代码。

3.水仙花数

水仙花数是指100到999之间某个数:个位的立方 + 十位的立方 + 百位的立方 = 某个数( 区间为[100,999] )
求[100,999]之前的水仙花数的程序如下:

int a = 1;
    int b = 0;
    int c = 0;
    for (int i = 100; i <=999; i++)
    {
        a = i%10;               //取出[100,999]之间某个数的个位
        b = i/ 100;              //取出[100,999]之间某个数的百位
        c = (i - a  - b * 100)/10;               //取出[100,999]之间某个数的十位
        if (a*a*a  + b * b * b + c*c*c == i)            //判断是否满足水仙花数的特征,当为true是执行if判断条件内的语句
        {
            Console.WriteLine("{0}是水仙花数", i);
        }
    }

4.输入数的正逆之和

Console.WriteLine("请输入一个正整数");            //在控制台上打印内容,Console为一个类,调用WriteLine方法
    try                        //防止用户输入的不是提示的内容
    {
            int number = Convert.ToInt32(Console.ReadLine());
            int a = number;
            for (int i = 0; i <= a; i++)
            {
                Console.WriteLine("{0}+{1}={2}", i, number--, number + 1 + i);
            }
    }
    catch                //当try内的代码执行出现错误时,执行该代码
    {
            Console.WriteLine("请输入正整数");
    }

当提示用户输入:请输入一个数字,此处输入的值为 6

5. 闰年、月份的判断

要求用户输入一个年份和月份:判断输入的年份是否是闰年及该年的这个月份有多少天

int year = 0;
    int month = 0;
    int day = 28;
    try
    {
        Console.WriteLine("请输入年份");
        year = Convert.ToInt32(Console.ReadLine());        //C#默认接收到用户的类型为string类型
        try
        {
            Console.WriteLine("请输入月份");
            month = Convert.ToInt32(Console.ReadLine());        //接收用户的输入并把输入的字符串类型转化为整型
            if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0)            //判断是否是闰年
            {
                Console.WriteLine("{0}年是闰年", year);
                if (month == 2)                //闰年的2月是一个特殊的月份,有29天
                {
                    day = 29;
                }
            }
            switch (month)            //判断月份有多少天
            {
 //在switch--case结构中,当case含有相同的代码时,只在最后一个case下写,其余的可以省略
                case 1:                                                                        
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                        Console.WriteLine("{0}年的第{1}个月有31天", year, month);               
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                        Console.WriteLine("{0}年的第{1}月有30天", year, month);
                    break;
                default:                //以上情况都不成立时执行
                    if (month <= 12 && month >= 1)          
                    {
                        Console.WriteLine("{0}年的第二个月有{1}", year, day);
                    }
                    else                // //防止用户输入的月份不在[1,12]之间
                    {
                        Console.WriteLine("请输入正确的月份!程序退出!!!");
                    }
                    break;            //default 的结尾
            }
        }
        catch                //当输入的月份格式不正确时执行;     2a, 8_ 等都为不正确的月份格式
        {
            Console.WriteLine("请输入正确的月份!程序退出!!!");
        }
    }
    catch                //当输入的年份格式不正确时执行;     2022a,1998_ 等都为不正确的年份格式
    {
        Console.WriteLine("请正确输入年份!程序退出!!!");
    }
    Console.ReadKey();                //暂停的作用,程序运行到这里暂停一下

当输入的年份是2000,月份为6时,程序执行结果如图5所示:

 当输入的年份是2022,月份为2时,程序执行结果如图6所示:

6.比较大小

比较三个数的大小并按从大到小输出

Console.WriteLine("请输入第一个数字");        //提示用户输入一个数字
    int a = Convert.ToInt32(Console.ReadLine());             //接收用户的输入并把输入的字符串类型转化为整型
    Console.WriteLine("请输入第二个数字");
    int b = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("请输入第三个数字");
    int c = Convert.ToInt32(Console.ReadLine());        //定义三个整型变量来接收用户输入的三个整数
    if (a > b)          //a>b
    {
            if (b > c)              //b>c
            {
                Console.WriteLine("{0},{1},{2}", a, b, c);
            }
            else if (c > a)             //b<c
            {
                Console.WriteLine("{0},{1},{2}", c, a, b);
            }
    }
    else if (c > b)                 //b>a
    {
        Console.WriteLine("{0},{1},{2}", c, b, a);
    }
    else if (c > a)                 //b>c>a
    {
        Console.WriteLine("{0},{1},{2}", b, c, a);
    }
    else                //a>c且b>a
    {
        Console.WriteLine("{0},{1},{2}", b, c, a);
    }

当提示用户输入时:输入的值分别是 5 , 1, 8 时,程序的执行结果如图所示:

7.冒泡排序

for循环的嵌套,将输入的数组按升序排列。

int[] nums = { 0, 9, 8, 5, 6, 5, 4, 3, 2, 1, 0 };
    for (int i = 0; i < nums.Length; i++)                        //nums.Length调用Length方法,计算数组nums[]的长度
    {
           for (int j = i + 1; j < nums.Length; j++)             //nums.Length调用Length方法,计算数组nums[]的长度
           {
                if (nums[i] > nums[j])
                {
                    nums[i] = nums[i] - nums[j];            //不使用第三方变量,交换两个数的值
                    nums[j] = nums[j] +nums[i];
                    nums[i] = nums[j] - nums[i];
                }
           }
    }
    for (int i = 0; i < nums.Length; i++)        //输出排序完成后的数组
    {
        Console.Write("{0} ",nums[i]);
    }
    Console.ReadKey();                //暂停程序,按任意键结束暂停

执行程序,程序的结果如图所示:

8.数组元素的调换

将数组中的元素首尾交换

string t=" ";            //定义一个字符串并赋初值
    string[] str = { "a", "b", "c","d","e","f" };
    for (int i = 0; i < str.Length/2; i++)              //str.Length调用Length方法,计算数组str[]的长度          
    {
        t = str[i];            //使用第三方变量交换两个数的值
        str[i]=str[str.Length-1-i];
        str[str.Length-1-i] = t;
    }
    for (int i = 0; i < str.Length; i++)
    {
        Console.Write(str[i]);
    }
    Console.ReadKey();

执行程序,程序的结果如图所示:

9.数组元素的输入输出 

输出数组中元素的和,最大值,最小值。

int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, };            //定义一个整型数组并赋值
    int max = a[0];                    //用数组中的元素赋值,防止输出的结果不是数组中的元素
    int min = a[0];
    int sum=0; 
    for (int i = 0; i < a.Length; i++)
    {
        if (a[i] > max)        //取出数组中的最大值
        {
            max = a[i];
        }
        if (a[i] < min)                //取出数组中的最小值
        {
            min = a[i];
        }
        sum +=a[i];            //将数组中的元素求和
    }
    Console.WriteLine("{0},{1},{2}",sum,max,min);

执行程序,程序的结果如图所示:

10.面向对象

namespace _01_面向对象
        {
            public class Person    //类不占内存,对象占内存,所以加载该项目时,类不被加载运行
            {
                public string? _names;              //字段
                public int _age;
                public string? _gender;
                public void CHLSS()                //定义一个方法
                {                                                                                               //this表示当前这个类的对象
                    Console.WriteLine("我叫{0},我今年{1}岁了,我是{2}生", this._names, this._age, this._gender);
                }
                public void CHLSSOne()                //定义一个方法,类中可以包含多个方法
                {                                                                                                   //this表示当前这个类的对象
                    Console.WriteLine("我叫{0},我今年{1}岁了,我是{2}生", this._names, this._age, this._gender);
                }
            }
        }

对类的调用

using _01_面向对象;                     //使用该命名空间下的类
        //类的实例化
            Person ZhangSan = new Person();         //使用之前先声明一个Person类的对象,对象调用类中的东西(属性,字段,方法)
        //声明声明一个对象的话要先声明一个类,对象包含各种属性,字段,方法
        ZhangSan._names = "张三";        //为类中的字段赋值
        ZhangSan._age = 24;        //为类中的字段赋值
        ZhangSan._gender = "男";        //为类中的字段赋值
        ZhangSan.CHLSS();       //调用类中的方法   对象.方法名
        Console.ReadKey();

        Person LiSi = new Person(); 
         //实例化一个对象李四  之后的操作就只针对对象操作
        LiSi._names = "李四";
        LiSi._age = 18;
        LiSi._gender = "女";
        LiSi.CHLSS();
        Console.ReadKey();

        Person WangWu = new Person();    
           //实例化一个对象王五,WangWu就相当于一个变量占内存,Person相当于int不占内存
        WangWu._names = "王五";           //实际上给字段赋了初值,在此设断点观察WangWud的值
        WangWu._age = 19; 
        WangWu._gender = "AB";
        WangWu.CHLSSOne();          //调用另外一个方法,类中可以包含多个方法
        Console.ReadKey();

执行程序,程序的结果如图所示:

        从输出可以看出王五的性别输出有误,原因是没有在类中对字段的赋值及取值进行限定。类中可以包含三部分字段、属性、方法。其中属性就是用来限定字段的赋值和取值的,要用到get(); set();方法。get();方法用来限定字段的取值,set();方法用来限定什么样的值才能赋值给字段。另外说一下类与结构的相似点及区别。
        struct结构与类都可以包含字段、属性、方法三部分。但是结构是面向过程的方法,而类是面向对象的方法,结构不包含类的三个基本特征:封装、继承、多态。
        文中存在不足的地方欢迎指正!!!

然后今天就讲到这里啦,大家记得点赞收藏,分享转发,关注小哥哥哦! 最后,如果你想学或者正在学C/C++编程,可以加入小编的编程学习C/C++企鹅圈https://jq.qq.com/?_wv=1027&k=vLNylJeG

  • 8
    点赞
  • 76
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
初学者的简单例题! private System.ComponentModel.IContainer components; private const int kNumberOfRows = 8; private const int kNumberOfTries = 3; private int NumTotalBricks = 0; private int NumBalls = 0; private Ball TheBall = new Ball(); private Paddle ThePaddle = new Paddle(); private System.Windows.Forms.Timer timer1; private Row[] Rows = new Row[kNumberOfRows]; private Score TheScore = null; private Thread oThread = null; [DllImport("winmm.dll")] public static extern long PlaySound(String lpszName, long hModule, long dwFlags); public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); for (int i = 0; i < kNumberOfRows; i++) { Rows[i] = new Row(i); } ThePaddle.Position.X = 5; ThePaddle.Position.Y = this.ClientRectangle.Bottom - ThePaddle.Height; TheBall.Position.Y = this.ClientRectangle.Bottom - 200; this.SetBounds(this.Left, this.Top, Rows[0].GetBounds().Width, this.Height); TheScore = new Score(ClientRectangle.Right - 50, ClientRectangle.Bottom - 180); // choose Level SpeedDialog dlg = new SpeedDialog(); if (dlg.ShowDialog() == DialogResult.OK) { timer1.Interval = dlg.Speed; } // // TODO: Add any constructor code after InitializeComponent call // } /// /// Clean up any resources being used. /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } private string m_strCurrentSoundFile = "BallOut.wav"; public void PlayASound() { if (m_strCurrentSoundFile.Length > 0) { PlaySound(Application.StartupPath + "\\" + m_strCurrentSoundFile, 0, 0); } m_strCurrentSoundFile = ""; oThread.Abort(); } public void PlaySoundInThread(string wavefile) { m_strCurrentSoundFile = wavefile; oThread = new Thread(new ThreadStart(PlayASound)); oThread.Start(); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.timer1 = new System.Windows.Forms.Timer(this.components); // // timer1 // this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(552, 389); this.KeyPreview = true; this.Name = "Form1"; this.Text = "Brick Out"; this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown); this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint); } #endregion /// /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Form1()); } private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { Graphics g = e.Graphics; g.FillRectangle(Brushes.White, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height); TheScore.Draw(g); ThePaddle.Draw(g); DrawRows(g); TheBall.Draw(g); } private void DrawRows(Graphics g) { for (int i = 0; i < kNumberOfRows; i++) { Rows[i].Draw(g); } } private void CheckForCollision() { if (TheBall.Position.X < 0) // hit the left side, switch polarity { TheBall.XStep *= -1; TheBall.Position.X += TheBall.XStep; PlaySoundInThread("WallHit.wav"); } if (TheBall.Position.Y this.ClientRectangle.Right - TheBall.Width ) // hit the left side, switch polarity { TheBall.XStep *= -1; TheBall.Position.X += TheBall.XStep; PlaySoundInThread("WallHit.wav"); } if (TheBall.Position.Y > this.ClientRectangle.Bottom - TheBall.YStep) // lost the ball! { IncrementGameBalls(); Reset(); PlaySoundInThread("BallOut.wav"); } if (RowsCollide(TheBall.Position)) { TheBall.YStep *= -1; PlaySoundInThread("BrickHit.wav"); } int hp = HitsPaddle(TheBall.Position); if (hp > -1)// lost the ball! { PlaySoundInThread("PaddleHit.wav"); switch (hp) { case 1: TheBall.XStep = -7; TheBall.YStep = -3; break; case 2: TheBall.XStep = -5; TheBall.YStep = -5; break; case 3: TheBall.XStep = 5; TheBall.YStep = -5; break; default: TheBall.XStep = 7; TheBall.YStep = -3; break; } } } private int HitsPaddle(Point p) { Rectangle PaddleRect = ThePaddle.GetBounds(); if (p.Y >= this.ClientRectangle.Bottom - (PaddleRect.Height + TheBall.Height) ) { if ((p.X > PaddleRect.Left) && (p.X PaddleRect.Left) && (p.X PaddleRect.Left + PaddleRect.Width/4) && (p.X PaddleRect.Left + PaddleRect.Width/2) && (p.X = kNumberOfTries) { timer1.Stop(); string msg = "Game Over\nYou knocked out " + NumTotalBricks; if (NumTotalBricks == 1) msg += " brick."; else msg += " bricks."; MessageBox.Show(msg); Application.Exit(); } } private void Reset() { TheBall.XStep = 5; TheBall.YStep = 5; TheBall.Position.Y = this.ClientRectangle.Bottom - 190; TheBall.Position.X = 5; timer1.Stop(); TheBall.UpdateBounds(); Invalidate(TheBall.GetBounds()); } private int SumBricks () { int sum = 0; for (int i = 0; i < kNumberOfRows; i++) { sum += Rows[i].BrickOut; } return sum; } private bool RowsCollide (Point p) { for (int i = 0; i < kNumberOfRows; i++) { if (Rows[i].Collides(TheBall.GetBounds())) { Rectangle rRow = Rows[i].GetBounds(); Invalidate(rRow); return true; } } return false; } private void timer1_Tick(object sender, System.EventArgs e) { TheBall.UpdateBounds(); Invalidate(TheBall.GetBounds()); TheBall.Move(); TheBall.UpdateBounds(); Invalidate(TheBall.GetBounds()); CheckForCollision(); NumTotalBricks = SumBricks(); TheScore.Count = NumTotalBricks; Invalidate(TheScore.GetFrame()); if (NumTotalBricks == kNumberOfRows*Row.kNumberOfBricks) { timer1.Stop(); MessageBox.Show("You Win! You knocked out all the bricks!"); Application.Exit(); } } private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { string result = e.KeyData.ToString(); Invalidate(ThePaddle.GetBounds()); switch (result) { case "Left": ThePaddle.MoveLeft(); Invalidate(ThePaddle.GetBounds()); if (timer1.Enabled == false) timer1.Start(); break; case "Right": ThePaddle.MoveRight(ClientRectangle.Right); Invalidate(ThePaddle.GetBounds()); if (timer1.Enabled == false) timer1.Start(); break; default: break; } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值