第06天

复习:

* for循环 已知循环次数

* 枚举 规范程序员开发

* int.tryParse false

* int.parse 抛异常

* 枚举和int之间的转换

* 枚举和string之间的转换

* 三元表达式 表达式1?表达式2:表达式3

* 常量 const 一旦声明就不能被重新赋值

* 数组 声明相同类型的变量

* 结构 声明不同类型的变量

 

demo:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace _02_数组

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            int sum = 0;

            for (int i = 0; i < nums.Length; i++)

            {

               // nums[i]  两种理解方式:1代表数组中当前循环到的这个元素  2、由于在循环中,也可以认为是数组

                //中的每一个元素

                sum += nums[i];

 

            }

            Console.WriteLine(sum);

            Console.ReadKey();

        }

    }

}

 

 

mini-ex:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

//练习1:从一个整数数组中取出最大的整数,最小整数,总和,平均值

 

namespace ex01

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] intArray = new[] {3, 1, 2, 4, 6, 5};

            int max = intArray[0];

            int min = intArray[0];

            int sum = 0;

 

 

            for (int i = 0; i < intArray.Length; i++)

            {

                if (max < intArray[i])

                {

                    max = intArray[i];

                }

                if (min > intArray[i])

                {

                    min = intArray[i];

                }

                sum += intArray[i];

            }

            Console.WriteLine("Max number: {0}", max);

            Console.WriteLine("Min number: {0}", min);

            Console.WriteLine("Sum is : {0}", sum);

            Console.WriteLine("Average is: {0}", sum*1.0/intArray.Length);

            Console.Read();

        }

    }

}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//练习2:计算一个整数数组的所有元素的和。
namespace ex02
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] intArray = new[] { 3, 1, 2, 4, 6, 5 };
            int sum = 0;
            for (int i = 0; i < intArray.Length; i++)
            {
                sum += intArray[i];
            }
            Console.WriteLine("Sum is: {0}", sum);
            Console.ReadLine();
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//练习3:数组里面都是人的名字,分割成:例如:老杨|老苏|老邹…”
//(老杨,老苏,老邹,老虎,老牛,老蒋,老王,老马)
 
namespace ex03
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] teacherNames = {"老杨", "老苏", "老邹", "老虎", "老牛", "老蒋", "老王", "老马"};
 
            string formattedString = "";
            for (int i = 0; i < teacherNames.Length; i++)
            {
                if (i < teacherNames.Length - 1)
                {
                    formattedString += teacherNames[i] + "|";
                }
                else
                {
                    formattedString += teacherNames[i];
                }
            }
            Console.WriteLine(formattedString);
            Console.Read();
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//练习4:将一个整数数组的每一个元素进行如下的处理:如果元素是正数则将这个位置的元素的值加1,如果元素是负数则将这个位置的元素的值减1,如果元素是0,则不变。
 
namespace ex04
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] intArray = {-2, 3, -1, 4, 6, 0, -8};
            int[] resultArray = new int[intArray.Length];
 
            for (int i = 0; i < intArray.Length; i++)
            {
                if (intArray[i] < 0)
                {
                    resultArray[i] = intArray[i] - 1;
                }
                if (intArray[i] > 0)
                {
                    resultArray[i] = intArray[i] + 1;
                }
                if (intArray[i] == 0)
                {
                    resultArray[i] = intArray[i];
                }
                
            }
            for (int j = 0; j < resultArray.Length; j++)
            {
                Console.Write("{0}\t",resultArray[j].ToString());
            }
           
            Console.ReadLine();
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//练习5:将一个字符串数组的元素的顺序进行反转。{“我”,“是”,”好人”} {“好人”,”是”,”我”}。第i个和第length-i-1个进行交换。
namespace ex05
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] strArray = {"我", "是", "好人"};
            string[] outputArray = new string[strArray.Length];
 
            for (int i = 0; i < strArray.Length; i++)
            {
                outputArray[strArray.Length - i - 1] = strArray[i];
            }
            for (int j = 0; j < outputArray.Length; j++)
            {
                Console.Write("{0}\t", outputArray[j]);
            }
            Console.ReadLine();
        }
    }
}

 

冒泡排序

int[] nums={9,8,7,6,5,4,3,2,1,0};    0,1,2,3,4,5,6,7,8,9

第一趟比较:8 7 6 5 4 3 2 1 0 9  交换了9次                 i=0    j=nums.Length-1-0;

第二趟比较:7 6 5 4 3 2 1 0 8 9  交换了9次 比较了 但是没交换 i=1   j=8 j=nums.Length-1-1;

第三趟比较:6 5 4 3 2 1 0 7 8 9  交换了7次                                   i=2 j=7 j=nums.Length-1-2

第四趟比较:5 4 3 2 1 0 6 7 8 9  交换了6次                  i=3 j=6

第五趟比较:4 3 2 1 0 5 6 7 8 9  交换了5次                  i=4 j=5

第六趟比较:3 2 1 0 4 5 6 7 8 9  交换了4次

第七趟比较:2 1 0 3 4 5 6 7 8 9  交换了3次

第八趟比较:1 0 2 3 4 5 6 7 8 9  交换了2次

第九趟比较:0 1 2 3 4 5 6 7 8 9  交换了1次

 

for(int i=0;i<nums.Length-1;i++)

{

       for(int j=0;j<nums.Length-1-i;j++)

       {

              if(nums[j]>nums[j+1])

              {

                     int temp=nums[j];

                     nums[j]=nums[j+1];

                     nums[j+1]=temp;

              }

       }

}

int[] nums = { 4, 8, 6, 5, 1, 2, 9, 7, 3, 0 };

Array.Sort(nums);//Sort这个方法只能对数组进行升序排列

 

int[] nums = { 4, 8, 6, 5, 1, 2, 9, 7, 3, 0 };

Array.Reverse(nums);//反转数组

 

方法(函数)

语法:

[public] static 返回值类型  方法名([参数列表])

{

       方法体;

}

public:访问修饰符,公开的,公共的

static:表示静态

返回值类型:如果没有返回值,写void

方法名:Pascal,要求每个单词的首字母都要大写。

参数列表:完成这个方法,所必须要提供给这个方法的条件。哪怕方法中不需要参数,小括号也不能省略。

 

参数:

返回值:

 

方法的调用:

类名.方法名([参数列表]);

 

///: 类或方法的注释

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ex06
{
    /// <summary>
    /// 写一个方法 返回两个数字中的最大值
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please input num 1:");
            int num1 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Please input num 2:");
            int num2 = Convert.ToInt32(Console.ReadLine());
            int result = Max(num1, num2);
            Console.WriteLine("Max number is {0}.", result.ToString());
            Console.ReadLine();
        }
 
        public static int Max(int num1, int num2)
        {
            int result = num1 > num2 ? num1 : num2;
            return result;
        }
    }
}

方法必须要写注释。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ex07
{
    /// <summary>
    /// 写一个方法 计算一个整数数组中的最大值
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            int[] inputArr = {3, 1, 2, 4, 7, 5, 6, 8};
            Console.WriteLine(MaxNumberInArray(inputArr));
            Console.ReadLine();
        }
 
        /// <summary>
        /// 计算一个整数数组中的最大值
        /// </summary>
        /// <param name="arr">传入的数组</param>
        /// <returns>数组中的最大值</returns>
        public static int MaxNumberInArray(int[] arr)
        {
            int result = arr[0];
            for (int i = 0; i < arr.Length; i++)
            {
                if (result < arr[i])
                {
                    result = arr[i];
                }
            }
            return result;
        }
    }
}

 

return

1)、在方法中返回要返回的值

2)、立即结束当前方法

 

调用者和被调用者的关系

我们在Main()函数中调用Test()函数,

我们管Main()函数叫做调用者,管Test()函数叫做调用者,管Test

被调用者。

如果被调用者想要得到调用者中的值:

1、传递参数

2、声明一个静态的字段,当做"全局变量"使用。

 

如果调用者想要得到被调用者中的值:

1、写返回值。

 

形参:形式上的参数,也会在内存中开辟空间。

实参:调用函数的时候传入的参数。

问题:形参和实参的名字必须一样么?

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ex08
{
    /// <summary>
    /// 写一个方法,判断一个年份是否是润年.
    /// </summary>
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Is {0} leap year?: {1}",2020,IsLeapYear(2020));
            Console.ReadLine();
        }
 
 
        public static bool IsLeapYear(int year)
        {
            if ((year%4 == 0 && year%100 != 0) || year%400 == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
 
    }
}

 

在写方法的时候需要注意

1、方法的功能一定要单一。

2、在方法中尽量的避免出现提示用户输入之类的代码。

 

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ex09
{
    /// <summary>
    /// 读取输入的整数,定义成方法,多次调用(如果用户输入的是数字,则返回,否则提示用户重新输入)
    /// </summary>
    internal class Program
    {
        private static void Main(string[] args)
        {
            Loop();
            Console.ReadLine();
        }
 
        public static void Loop()
        {
            while (true)
            {
                Console.WriteLine("Please input a number:");
                int number;
                if (int.TryParse(Console.ReadLine(), out number))
                {
                    return;
                }
                else
                {
                    continue;
                    
                }
            }
        }
    }
}
 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ex10
{
    /// <summary>
    /// 还记得学循环时做的那道题吗?只允许用户输入y或n,请改成方法
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            Loop();
            Console.ReadLine();
        }
 
        public static void Loop()
        {
            while (true)
            {
                Console.WriteLine("Continue?(y or n)");
                string input = Console.ReadLine();
 
                if (input == "y")
                {
                    continue;
                }
                else if (input == "n")
                {
                    Console.WriteLine("Thank you");
                    return;
                }else {
                    Console.WriteLine("Error");
                    continue;
                }
            }
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ex11
{
    /// <summary>
    /// 查找两个整数中的最大值:int Max(int i1,int i2)
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter first number:");
            int num1 = int.Parse(Console.ReadLine());
            Console.WriteLine("Please enter second number:");
            int num2 = int.Parse(Console.ReadLine());
 
            Console.WriteLine("Max number is {0}.", Max(num1, num2).ToString());
            Console.ReadLine();
        }
 
        public static int Max(int i1, int i2)
        {
            return i1 > i2 ? i1 : i2;
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ex12
{
    /// <summary>
    /// 计算输入数组的和:int Sum(int[] values)
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            int[] myArray = {1, 2, 3, 4, 5};
            int sum = Sum(myArray);
            Console.WriteLine("Array sum is: {0}.", sum.ToString());
            Console.ReadLine();
        }
 
        public static int Sum(int[] values)
        {
            int sum = 0;
            for (int i = 0; i < values.Length; i++)
            {
                sum += values[i];
            }
            return sum;
        }
    }
}

 

demo:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace _11_让方法返回多个值

{

    class Program

    {

        static void Main(string[] args)

        {

           

            //写一个方法 让这个方法返回一个数组的最大值、最小值、总和、平均值

            int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            int[] numsNew = GetMaxMinSumAvg(nums);

            Console.WriteLine("这个数组的最大值是{0},最小值是{1},总和是{2},平均值是{3}",numsNew[0],numsNew[1],numsNew[2],numsNew[3]);

            Console.ReadKey();

        }

 

        /// <summary>

        /// 返回一个数组的最大值、最小值、总和、平均值

        /// </summary>

        /// <param name="nums"></param>

        /// <returns></returns>

        public static int[] GetMaxMinSumAvg(int[] nums)//string double bool

        {

            int[] numsNew = new int[4];

            //numsNew[0]最大值  numsNew[1]最小值 numsNew[2]总和 numsNew[3]平均值

            numsNew[0] = nums[0];//int max=nums[0]

            numsNew[1] = nums[0];//int min=nums[0]

            numsNew[2] = 0;

            for (int i = 0; i < nums.Length; i++)

            {

                if (nums[i] > numsNew[0])

                {

                    numsNew[0] = nums[i];

                }

                if (nums[i] < numsNew[1])

                {

                    numsNew[1] = nums[i];

                }

                numsNew[2] += nums[i];

            }

            numsNew[3] = numsNew[2] / nums.Length;

            return numsNew;

        }

 

    }

}

 

 

out参数

可以帮助我们在一个方法中返回多个值,不限类型。

使用out参数的时候要求,out参数必须在方法内为其赋值。

 

demo:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace _12out参数

{

    class Program

    {

        static void Main(string[] args)

        {

            int n;

            bool b;

            string s = Test(out n, out b);

            Console.WriteLine(s);

            Console.WriteLine(n);

            Console.WriteLine(b);

            Console.ReadKey();

        }

 

        public static string Test(out int number, out bool b)//我想再返回一个int类型的100

        {

            number = 100;

            b = false;

            return "张三";

        }

    }

}

 

 

mini-ex:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ex13
{
    /// <summary>
    /// 写一个方法判断用户是否登陆成功
    /// 如果登陆成功返回一个true,并且返回一条登陆信息
    /// 如果登陆失败,返回一个false,返回一条错误信息
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            string outputMessage;
            bool flag = Login(out outputMessage);
            if (flag)
            {
                Console.WriteLine("Login successful. {0}", outputMessage);
            }
            else
            {
                Console.WriteLine("Login Error, {0}.", outputMessage);
            }
 
            Console.ReadLine();
        }
 
        public static bool Login(out string message)
        {
            Console.WriteLine("Please enter username:");
            string username = Console.ReadLine();
            Console.WriteLine("Please enter password:");
            string password = Console.ReadLine();
 
            if (username == "admin" && password == "88888")
            {
                message = "Welcome";
                return true;
            }else if (username != "admin")
            {
                message = "Username error.";
                return false;
            }
            else if (password != "88888")
            {
                message = "password error.";
                return false;
            }
            else
            {
                message = "username and password error";
                return false;
            }
        }
    }
}

 

mini-ex:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace _14out参数练习

{

    class Program

    {

        static void Main(string[] args)

        {

            //使用out参数返回一个数组的最大值、最小值、总和、平均值

            int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            int max;

            int min;

            int sum;

            int avg;

            GetMaxMinSumAvg(nums, out  max, out min, out sum, out avg);

            Console.WriteLine(max);

            Console.WriteLine(min);

            Console.WriteLine(sum);

            Console.WriteLine(avg);

            Console.ReadKey();

        }

 

        public static void GetMaxMinSumAvg(int[] nums, out int max, out int min, out int sum, out int avg)

        {

            max = nums[0];

            min = nums[0];

            sum = 0;

            for (int i =0; i < nums.Length; i++)

            {

                if (nums[i] > max)

                {

                    max = nums[i];

                }

                if (nums[i] < min)

                {

                    min = nums[i];

                }

                sum += nums[i];

            }

            avg = sum / nums.Length;

        }

    }

}

 

 

demo:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace _15自动动手写TryParse

{

    class Program

    {

        static void Main(string[] args)

        {

            // int.TryParse()

            int result = 100;

            bool b = MyTryParse("123abc", out result);

            Console.WriteLine(b);

            Console.WriteLine(result);

            Console.ReadKey();

            //无--有   总结

            //有--很多

        }



        /// <summary>

        /// 将字符串转换成int类型

        /// </summary>

        /// <param name="s">要转换的字符串</param>

        /// <param name="result">转换成功后的整数</param>

        /// <returns></returns>

        public static bool MyTryParse(string s, out int result)

        {

            try

            {

                result = Convert.ToInt32(s);

                return true;

            }

            catch

            {

                result = 0;

                return false;

            }

        }

    }

}

 

 

posted @ 2017-05-24 22:44  摩羯红梅  阅读(232)  评论(0编辑  收藏  举报