第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;

}

}

}

}

时间: 2024-08-18 16:16:16

第06天的相关文章

【C++基础 06】explict关键字

C++提供了关键字explicit,可以阻止不应该允许的经过转换构造函数进行的隐式转换的发生.声明为explicit的构造函数不能在隐式转换中使用. 1.示例 我们先来看一段示例代码: class A { public: A(int v):var(v){};//带一个int型值的构造函数 bool isSame(const A& ref) const {return var == ref.var;}//判等函数 private: int var;//成员变量var }; void main()

初尝Mcafee之在ePO中进行策略和客户端任务设置【06】

一.策略和客户端任务概述 在ePO中点击"菜单",可以看到一个策略的大分类:ePO就是通过分配策略和客户端任务给客户端代理,然后代理将这些策略和客户端任务分配给本地相应的Mcafee杀毒防护软件进行执行: 策略是针对软件的内在参数和计划任务的配置,例如VirusScan是否扫描压缩文件,VirusScan的扫描计划的设置: 客户端任务是针对软件的外在交互,例如安装,部署,更新,信息统计等: 二.策略和客户端任务的分配结构: 策略和客户端任务的分配结构有点跟Windows Server的

java进阶06 线程初探

线程,程序和进程是经常容易混淆的概念. 程序:就是有序严谨的指令集 进程:是一个程序及其数据在处理机上顺序执行时所发生的活动 线程:程序中不同的执行路径,就是程序中多种处理或者方法. 线程有两种方法实现 一:继承Thread 覆盖run方法 package Thread; public class Thread1 { public static void main(String[] args){ MyThread1 thread1=new MyThread1(); thread1.setName

1099:零起点学算法06——再来一题除法算术题

1099: 零起点学算法06--再来一题除法算术题 Time Limit: 1 Sec  Memory Limit: 128 MB   64bit IO Format: %lldSubmitted: 4811  Accepted: 1917[Submit][Status][Web Board] Description 再来一题除法算术题 Input 没有输入 Output 输出8除以5,保留1位小数 Sample Output 1.6 Source 零起点学算法 1 # include <std

06月19日【迅雷王】已更新可用迅雷会员114个

关注迅雷王迅雷王博客中的所有迅雷账号由Python程序自动验证可用后发送到Blog中供大家免费享用,如果很快被查封可以扫描微信二维码免费领取每日专享迅雷VIP账号! [迅雷王Blog]ID:xunleiaccount 按[Ctrl + D]收藏 [迅雷王]迅雷账号_迅雷王坚持在博客园至少每天更新10个可用迅雷账号!06月19日[迅雷王]已更新可用迅雷会员114个 [迅雷王迅雷钻石会员]81267[密码]size517984 [迅雷王迅雷钻石会员]tlxnvyw[密码]tlxnvyw:240735

数组-06. 找出不是两个数组共有的元素

数组-06. 找出不是两个数组共有的元素(20) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 张彤彧(浙江大学) 给定两个整型数组,本题要求找出不是两者共有的元素. 输入格式: 输入分别在2行中给出2个整型数组,每行先给出正整数N(<=20),随后是N个整数,其间以空格分隔. 输出格式: 在一行中按照数字给出的顺序输出不是两数组共有的元素,数字间以空格分隔,但行末不得有多余的空格.题目保证至少存在一个这样的数字.同一数字不重复

*结构-06. 复数四则运算

1 /* 2 * Main.c 3 * F6-结构-06. 复数四则运算 4 * Created on: 2014年8月26日 5 * Author: Boomkeeper 6 ********部分通过*********** 7 */ 8 9 #include <stdio.h> 10 #include <math.h> 11 12 #define EPSINON 0.1 13 14 /* 15 * 复数结构体,c1.c2对应于题目中的c1.c2 16 */ 17 struct c

字符串-06. IP地址转换

1 /* 2 * Main.c 3 * D6-字符串-06. IP地址转换 4 * Created on: 2014年8月19日 5 *******测试通过******** 6 *转载:http://blog.csdn.net/junjieguo/article/details/7392539 7 */ 8 9 10 #include <stdio.h> 11 12 int bin_dec(int x, int n) //自定义函数将二进制数转换为10进制 13 { 14 if(n == 0)

使用XCB编写X Window程序(06):XCB取代Xlib的理由

我经常访问Xorg的官网,希望能找到一些对理解Linux和X Window有用的东西.结果也确实是偶有所得.比如,在Xorg的官网中就建议大家不用Xlib了,改用XCB.不可否认,Xlib确实是一个比较老的东西,老到最新的一本关于Xlib的书都已经是N多年前出版的了.有了Xorg官方的指导,我自然不用学Xlib了,直接上XCB. 经过这一段时间的学习,对XCB有了一定的了解.我的学习是根据XCB官方的教程来的,当然,如果有一点点在GUI编程领域的经验和悟性学习起来会更加事半功倍.在XCB的官方教

Aldec.Riviera-Pro.v2013.06.Win64 1CD+开目KMCAD2014

Intergraph SmartPlant 3D 2011 R1 v09.01.30.0055 1DVD  MITCalc.v1.7 1CD  RockWare.QuickSurf.2013.v6.0.121202.AutoCAD.2013-2014 Win32_64 2CD  CAMWorks2014 SP1.0 for SolidWorks 2013-2014 Multilanguage Win32_64 2DVD  MSC Digimat v4.4.1 Win64 1CD  RecurDy