您的位置:首页 > 职场人生

黑马程序员_C#编程基础

2013-11-10 20:21 851 查看

------- Windows Phone 7手机开发.Net培训、期待与您交流! ------- 

 

基础知识

.net和C#的区别

1. .NET/dotnet:一般指.Net Framework框架,一种平台,一种技术

2. C#(sharp):一种编程语言,可以开发基于.net平台的应用

3. (*)JAVA即是一种技术也是一种语言
.net可以干什么

1. 在.net这个平台上开 发桌面应用程序 叫做winform应用程序开发

2. Internet应用程序 ASP.net

3. 手机开发:wp7

4. C/S 客户机[winform](Client)/服务器(Server)

5. B/S 浏览器/服务器模式 [通过浏览器访问]
IDE介绍

1. IDE(Integrated Development,集成开发环境)

2. Visual Studio 简介:

一套完整的开发工具集

用于开发桌面的应用程序、ASP.NET WEB一用程序、XML、Web Service、移动应用程序

为快速开发提供强大支持
MSDN介绍

1. MSDN 的全称是 Microsoft Developer Network。这是微软公司面向软件开发者的一种信息服务。MSDN 实际上是一个以 Visual Studio 和 Windows 平台为核心整合的开发虚拟社区,包括技术文档、在线电子教程、网络虚拟实验室、微软产品下载(几乎全部的操作系统、服务器程序、应用程序和开发程序的正式版和测试版,还包括各种驱动程序开发包和软件开发包)、Blog、BBS、MSDN WebCast、与 CMP 合作的 MSDN 杂志等等一系列服务。
Visual studio应用
1. 选择Visual C#语言

2. 选择应用程序控制台

3. 名称

4. 位置(Visual Studio 2008)

5. 解决方案(Visual Studio 2008)



1. 在.net这个平台上开始桌面应用程序,叫做Winform应用程序开发。

2. 解决方案中可以包含多个项目,项目可以包含多个文件,文件中是我们写的程序。
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

-引用命名空间

namespace Programs

{

    class Program

    {

        static void Main(string[] args)

        {

        }

    }

}

-定义了一个命名空间,叫:Programs

class Program

    {

        static void Main(string[] args)

        {

        }

    }

-定义了一个名称为Programm的类

static void Main(string[] args)

        {

        }

-这是一个方法,叫做Main



3. 在文件中,命名空间中可以包含类,类中可以包含方法,方法中可以是我们写的程序。

4. 一般窗口不小心关闭了,在视图中寻找。

5. 重置开发环境,可以是我们的开发环境还原为默认状态。

工具-导入和导出设置-重置所有设置-否,仅重置所有设置~。

5. Main方法是我们程序的入口方法,当我们执行一个程序时,会首先找到一个Main方法,从Main的第一句程序开始执行,当Main方法执行完成后(即执行到Main方法的反大括号就结束了)。

6. 初学者写程序,就先写在Main方法中。

1. 解决方案-在WINDOWS资源管理器中打开文家夹

2. .sln是解决方案文件

3. .csproj是项目文件

4.

            Console.WriteLine("你想显示的内容");

5.

            Console.ReadKey();

当程序执行到Console.ReadKey();时,程序会停到这里,等待用户从键盘上键入后,程序才继续执行

6. 在C#中,每一句话都必须以“分号”结束

7. 工具-选项-字体和颜色

8. 工具-选项-文本编辑器-行号(勾选)

9. 解决方案-新建项目(在当前解决方案下新建项目)

10. 项目-设置为启动项目

11. WriteLine,光标出现在下一行

12. Write,光标出现在这句话后面

13. 解决方案-属性-单启动项目

C#中的注释

1. 什么是注释呢?对我们写的程序写的解释,注释是给人看的。

2.

第一种:单行注释,以//开始,到本行结束

第二种:多行注释/*开始 /*结束,之间的都为注释

第三种:文档注释,用于对类和方法进行注释

,在类或方法前面连续输入3个/

Visual Stodio中的快捷键
1. Home 无论光标在哪,按下后跳转到该行最前面

2. End 无论光标在哪,按下后跳转到该行最后面

3. Page up 上翻一页

4. Page down 下翻一页

5. Shift 选中多个字符

6. Ctrl+Home 整个文档最前面

7. Ctrl+End 整个文档最后面

8. Delete 删除光标后面的

9. Backspace 删除光标前面的

10. Insert 覆盖字符

11. over 插入字符

12. Ctrl Z/X/C/V 撤销/剪贴/复制/粘贴

12. F5调试程序

13. F6生成程序

14. #Region和#Endregion 折叠语段
            #region 我的第一个程序

            Console.WriteLine("***************************");

            Console.WriteLine("*   这是我的第一个程序    *");

            Console.WriteLine("***************************");

            Console.ReadKey();

            #endregion


.Net 是一种多语言的平台,开发.Net可以用多达几十种语言进行开发

Java 是一种单语言的平台,一种语言多平台

软件系统依赖关系

VC++.NET        C#         VB.NET        VJ#

.NET Framework 类库 (FCL)

公共语言运行库

操作系统

.NET是如何实现语言无关性的

MSIL:微软中间语言

.NET Framework
Web 窗体        Web Service        WinForms

ADO.NET 和 XML 类

基本框架类

CLR:公共语言运行时

CLS:公共语言规范

CTS:通用类型系统

JIT:即时编译器

  
C#中的注释符

//单行注释

/**/多行注释

///

///文档注释

///

用户存储正在运行的程序数据(不准备)

RAM:内存有个特点,断电后里面的数据丢失。

变量:变量代表着一块内存空间,我们可以通过变量名称向内存存/取数据,有变量就不需要我们记忆复杂的内存地数据类型

整数字在C#中的数据类型叫做INT

int  number

a=1000   //把1000放进去

赋值: 变量名=值

PS:number加引号显示number,不加引号显示值

<
4000
h3>数据类型



数值:

1.整型:int

        ......

   非整型:double   (小数)

                decimal  (金钱)

2.非数值

char

String

 
变量的使用和命名规则

int 所包含的值前后20万

double:小数

char:字符型     只能存储一个字符,并且存储的这个字符要求用单引号引起来

string:字符串   把0个或1个或多个字符连接以来,字符串要求用双引号连接起来

int: 3 5 100

double:  3.14   10.5   -3.14

char:   'A'   'b'   'a'

string:  "zhangsan"   "李四"  "计算"

decimal:(存储金钱)5.26

decimal d=5.55m

十几位以上的数字用decimal

十几位以下用double

注意:在C#开发环境中,直接写一个有小数点的数字,这个数字是double类型的。

在一个小数后面加一个m/M,就告诉编译器这个数字是decimal。

 
变量声明的三种方法:
1.先声明后赋值   int a;  a=3

2.定义变量时直接赋值   int a=3;

3.可以一次声明多个同类型的变量,多个变量之间用,相隔最后以;结束
 string zsname, lsname, wwname;

            zsname = "zs";

            lsname = "ls";

            wwname = "ww"
 
变量的命名规则:
1.必须以“子母”或@符号

2.后面可以跟任意“子母”,数字,下划线

注意

1.起的变量名不要和c#系统中的关键字重复(关键词会变为蓝色)

2.在c#中,大小写是敏感的

3.同一个变量名不允许重复定义(不严谨)

定义变量时,变量名要有意义

c#变量名编码规范

Camel  命名法:

首个单词的首字母小写,其余单词的的首字母大写

Pascal ,命名规范:

每个单词的第一个字母都大写

如果使用到英文单词的缩写,全部使用大写

 
输出变量的值连_赋值符_连接符_占位符

赋值运算符:=

a=a+1; 这里的=号是赋值运算符,不是数学意义上的相等。

变量可以重复赋值,一旦给一个变量赋了新值,那么变量中的老值就不复存在了。

右边代码的输出结果:
int age = 10;

age = 20;

Console.WriteLine(age);

在方法中定义变量,要使用Camel命名法,Main方法也是。

在一个方法中,一般情况下变量只能定义一次,但可以多次赋值,再次赋值时会把变量中原有的值覆盖掉。

“+”在C#中有两个意义
1.是数学中的加法运算:两边参与加法运算的数据类型为数字类型,则“+”表示数学上的加法的意义

2.是连接意义:两边参与加号运算的数据,有一个是字符类型,那么这个“+”就是连接意义
 string a = "1";

            int b = 2;

            Console.WriteLine(a+b);
输出的值为12
 

我叫张三,今天28岁了,我的工资是7800.33元
  string newname = "张三";

            int newage = 28;

            decimal newmoney = 7600.33m;

            Console.WriteLine("我叫" + newname + ",今年" + newage + "岁了,我的工资是"+newmoney+"元");

 
Consolo.Writeline引号中的原封不动输出

在Conslole.Writeline("")中,第一个变量/字符串中可以使用占位符

占位符由{数字}组成,数字由0开始编号

第一个占位符:{0}

第二个占位符:{1}

第三个占位符:{2}

我叫张三,今天28岁了,我的工资是7800.33元

Console.WriteLine("我叫" + newname + ",今年" + newage + "岁了,我的工资是"+newmoney+"元");

Console.WriteLine("我叫{0},今年{1}岁了,我的工资是{2}元",newname,newage,newmoney);

Console.Wroteline();有多个参数时,输出都是第一个参数中的内容,从第二个参数开始,都是用来替换第一个参数中的占位符的值,所以从第二个参数开始,要不要输出,就看第一个参数中有没有想过的占位符。

今天28岁了,我的工资是7800.33元我叫张三,今天28岁了,我的工资是7800.33元

Console.WriteLine("{0}我叫"+newname,"今年"+newage+"岁了,我的工资是"+newmoney+"元");

 

变量交换_输入

 
长数字用string
            string wname="张三";

            int wage=18;

            char wsex='男';

            string phone="010-110-2";

            Console.WriteLine("我叫{0},今年{1}岁了,性别{2},电话{3}",wname,wage,wsex,phone);
变量交换

            int a = 10;

            int b = 5;

            int temp;

            temp = a;

            a = b;

            b = temp;

            Console.WriteLine("a={0},b={1}",a,b);

用于让用户从键盘上输入一句话,当程序执行到下面这句话,就会暂停,然后等待用户从键盘上输入一句话,按回车程序会继续执行。如果想得到用户输入的内容,就需要定义一个string类型的变量,写在下面这句话前面接受用户输出的内容。

Console.ReadLine().

接受用户输入的内容,必须定义一个字符串来进行接受

string input=Consloe.ReadLine();

数据类型的自动转换
练习一
            Console.WriteLine("请输入你喜欢吃的水果?");

            string input = Console.ReadLine();

            Console.WriteLine("这么巧啊,我也喜欢吃{0}",input);

            Console.ReadKey();

练习二

            Console.WriteLine("请问你叫什么名字?");

            string name = Console.ReadLine();

            Console.WriteLine("你好,{0}", name);

转义字符:
当我们需要在字符串中输入一些特殊字符时,比如:半角引号,换行,退格,就需要使用转义字符。

转义字符是一个字符,

在屏幕上显示:c#用的字符用“”包含起来

\+一个字符,组成转义字符,他由一个\+一个子母来组成具有特殊意义的一个字符

            Console.WriteLine("c#中的字符要用\"\"引起来");

                               c#用的字符用“”包含起来
常用的转义字符
\n  换行

            Console.WriteLine("1\n2");

\b baskspace 退格

            Console.WriteLine("1\b2\b3");

\t tab键 由多个空格组成的一个字符,具有行与行之间的对其功能

            Console.WriteLine("1\t2\t3\t4\t5\t");

            Console.WriteLine("1\t22\t333\t4444\t55555\t");

\\ 表示一个\

在字符串前面加@符号有两种意义
1.字符串中如果有\,则不再理解为转义符。

            Console.WriteLine(@"C:\Users\Zank\Desktop\NET听课笔记");

2.使字符串可以换行

            Console.WriteLine(@"C:\Users\Zank

            \Desktop

            \NET听课笔记");

如果字符串前面加了@符号,在字符串上用两个双引号代表一个双引号

            Console.WriteLine(@"C:\Users\Zank""\Desktop\NET听课笔记");
 

算术运算符及算数表达式
算术运算符: + — * / % (去余数 取模)

算数表达式:由算数运算符连接起来的式子。如:1+1  a-b  (变量ab前面已经声明并赋初值)

优先级:先乘除,后加减,有括号先算括号里面的,相同级别从左至右运算

小括号可以无限制的套用,但一定要成对出现。

            int chinese = 90;

            int math = 80;

            int english = 91;

            int sun = chinese + math + english;

            int avg = sun / 3;

            Console.WriteLine("您的总成绩是{0},平局成绩是{1}", sun, avg);

c#中,有五个算数运算符: + — * / %   他们都是二元运算符。

            //double pi = 3.14;

            //int r = 5;

            //double s = r * r * 3.14;

            //Console.WriteLine("s={0}",s);

要求:参与运算的两个操作数的类型必须相同,并且经过运算后的结果也与操作数的类型相同。

            double tshirPrice = 35;

            double trouserPrice = 120;

            double totalMoney = 3 * tshirPrice + 2 * trouserPrice;

            double disMoney = totalMoney * 0.88;

            Console.WriteLine("购物总计:{0},打8.8折后应付:{1}元", totalMoney, disMoney);
 

发生自动转换的条件

1.参与运算的两个数据类型必须相兼容

2.必须一边的数据类型表示范围小,一边的范围大,比且把小的转向大的不丢失精度

Double中包含int

            //int a = 10, b = 3;

            //int mod = a % 3;       【%取余数,输出1】

            //double quo = a / b;    【/取模,输出3,将int转化为double类型】

            //Console.WriteLine("mod={0}   quo={1}", mod, quo);

一个表达式,如果其中一个操作数为double类型,那么整个数为double类型(double的精度为15)

            int a = 10, b = 3;

            int mod = a % 3;     

            double quo = 1.0*a / b;

            Console.WriteLine("mod={0}   quo={1}", mod, quo);

这里quo输出的值为3.333333333333333,为double类型,这是double除以double,如果为int除以double则显示3

 

 

字符串无法强制转换成数字类型

Convert不再仅是内存级别的转换,而是老驴数据意义的转换。

Convert是一个加工、改造的过程

Convert.ToInt32(待转换字符串)

Convert.Tostring每种类型都还有.ToString()方法

一切类型都可以转换成为string类型

int 变量=Consvert.ToInt32(待转字符串)

上面语句的意义:把待转字符串转换成int类型后赋给变量

string strsCore="90";

int iScore = Convert.ToInt32(strScore);

把strScroe转化成int类型并且付给iScroe

            Console.WriteLine("请输入你的语文成绩?");

            string chinese = Console.ReadLine();

            Console.WriteLine("请输入你的数学成绩?");

            string math = Console.ReadLine();

            int chineseScroe = Convert.ToInt32(chinese);

            int mathScroe =Convert.ToInt32(math);

 

            Console.WriteLine("你的总成绩为:{0}",chineseScroe + mathScroe);

缩写直接赋值

            int chinese =Convert.ToInt32( Console.ReadLine());

 

c#中异常捕获如何来完成:
try

{

     有可能出现的错误的代码卸载这里



catch

{

     出错后的处理

}

上面的程序如何执行“

如果try中的代码没有出错,则程序正常运行try中的内容后,不会执行catch中的内容

如果try中的代码一旦出错,程序立即跳入catch中去执行代码,那么ray中的出错代码后面的内容

            //第一题

            //让学生输入其姓名和语文\数学\英语,编程求总分和平均分

            //并在屏幕上显示:XX你的总分为xx分,平均分为XX分

            try

            {

                Console.WriteLine("请输入您的姓名:");

                string name = Console.ReadLine();

                Console.WriteLine("请输入您的语文成绩:");

                int chinese = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("请输入您的数学成绩:");

                int math = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("请输入您的英语成绩");

                int english = Convert.ToInt32(Console.ReadLine());

                int point = chinese + math + english;

                int average = Convert.ToInt32((chinese + math + english) / 3);

                Console.WriteLine("您的姓名是{0},您的总分是{1},您的平均分是{2}", name, point, average);

            }

            catch

            {

                Console.WriteLine("您刚才输入的数据有误导致程序出错,请重新运行程序!");

            }

            Console.ReadKey();
 

            //第二题

            //编程实现计算几天(如46天)是几周零几天.   46/7...4

            Console.WriteLine("请输入你要计算的天数?");

            int days = Convert.ToInt32(Console.ReadLine());

            int week = days / 7;

            int mod = days % 7;

            Console.WriteLine("{0}中共有{1}周{2}天",days,week,mod);

            Console.ReadKey();

            //第三题<
1e397
br />
            //编程实现计算几天(如46天)是几月几周零几天.

            Console.WriteLine("请输入你要计算的天数?");

            int days = Convert.ToInt32(Console.ReadLine());

            int mouth = days / 30;

            int week = (days-mouth*30) / 7;

            int mod = (days-mouth/7) % 7;

            Console.WriteLine("{0}中共有{1}月{2}周{3}天", days,mouth, week, mod);

            Console.ReadKey();
            //第四题

            //编程实现107653秒是几天几小时几分钟几秒钟?

            int seconds = Convert.ToInt32(Console.ReadLine());

            int day = seconds / (3600 * 24);

            int mod = seconds % (3600 * 24);      //除去上面的天数还剩多少秒

            int hour = mod / 3600;                //看看剩余的秒数中海油多受啊3600秒

            int min = mod / 60;                   //看看剩余的秒数中除去上面算的小时,还剩余多少时间

            int second = mod % 60;

            Console.WriteLine("{0}秒中共包含{1}天{2}小时{3}分钟{4}秒",seconds,day,hour,min,second);

            Console.ReadKey();

自加自减复合赋值-关系表达式

 

++ 自加一 有前加和后加

-- 自减一 有前减和后减
            int age = 18;

            age = age + 1;

            age++;

            age--;

            Console.WriteLine("age={0}",age);

            Console.ReadKey();

            int age = 18;

            int sum = age++ - 10;

            Console.WriteLine("age={0}", age);

            Console.WriteLine("sum={0}", sum);

            Console.ReadKey();

            //输出:age19   sum8

上面代码中age是后加,所以在进行语句运算时,age++取原值参与运算,所以sum=8

            int age = 18;

            int sum = ++age - 10;

            Console.WriteLine("age={0}", age);

            Console.WriteLine("sum={0}", sum);

            Console.ReadKey();
            //输出:age19   sum9

上面代码中age是前加,所以在进行语句运算时,++age取加一后的新值参与运算,所以sum=9

int age = 8;

int sum = age++ - 10;

相当于:

int age = 18;

int sum = age - 10;

age = age + 1;

int age = 8;

int age = ++age - 10;

相当于:

int age = 18;

age = age + 1;

int sum = age -10

c#中一元二次运算符高于二元二次运算符
            int var1;

            int var2 = 5;

            int var3 = 6;

            var1=var2++ * --var3;

            Console.WriteLine("var1={0},var2={1},var3={2}",var1,var2,var3);

            Console.ReadKey();

            //输出var1=25,var2=6,var3=5.

+=  

例如:age=age+3     =      age+=3;

;理解成在age的原值上加3

-=

例如:age=age-3     =      age-=3;

;理解成在age的原值上减3

*=

/=

%=

能够改变变量值的:

++/--

=

关系运算符
在c#中,有6个关系运算符,用于比较两个事物之间的关系。

>

<

==  比较相等

!=  比较不相等

>=

<=

关于表达式:由关系运算符链接起来的式子

布尔(bool)类型

真:ture

假:false

关系表达式的运算结果为bool类型,bool类型只有两个值,一个是ture,一个是false。

如果关系运算表达式成立,则这个表达式的值为ture,否则为false

            int zsage = 20;

            int lsage = 18;

            bool isRight = zsage < lsage;

            Console.WriteLine(isRight);

 

逻辑表达式
 

字符类型可以比较大小

            int dxZL = 1500;

            int lsZL = 1;

            bool isRight = dxZL > lsZL;

            Console.WriteLine(isRight);

            Console.ReadKey();

字符串类型不能比较大小

            string zsName="zhangsan";

            string lsName = "lisi";

            bool isRight = zsName != lsName;

            Console.WriteLine(isRight);

            Console.ReadKey();

 

逻辑运算符: &&  ||   !
逻辑与运算:&&
bool isRight = 表达式1 && 表达式2

逻辑与连接的两个表达式,要能够求解成bool类型,一般情况都是关系表达式

整个逻辑与运算的结束也是bool类型

表达式1       表达式2     逻辑与结果

ture      tureture

false      false   false

false      ture              false

ture      false             false

当两个表达式全为ture时,结果才为ture

            int age = 20;

            int weight = 120;

            bool result = age >= 18 && weight >= 100;

            Console.WriteLine(result);

输出的结果为Ture

            int age = 10;

            int weight = 90;

            bool result = age >= 18 && weight >= 100;

            Console.WriteLine(result);

输出的结果为False

 
逻辑与运算:||

bool isRight = 表达式1 || 表达式2

逻辑与连接的两个表达式,要能够求解成bool类型,一般情况都是关系表达式

整个逻辑与运算的结束也是bool类型

表达式1       表达式2     逻辑与结果

ture      tureture

false      false   ture

false      ture              ture

ture      false             false

只要有一个为ture,其结果都为ture

            //让用户输入张三的身高和体重

            //火车站规定,一个人的身高>=120厘米或者体重>=50kg就必须买票

            //需要买票输出ture,不需要输出false

            Console.WriteLine("请输入您的身高(cm):");

            int high = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("请输入您的体重(kg):");

            int weight = Convert.ToInt32(Console.ReadLine());

            bool result = high >= 120 || weight >= 50;

            Console.WriteLine(result);
逻辑非:!

这是一个一元运算符.

用法:

!(布尔类型的表达式)

作用:

如果:

布尔类型的表达式的表达式为ture,加!号后,其整个式子的结果为false.

布尔类型的表达式的表达式为false,加!号后,其整个式子的结果为ture.

            Console.WriteLine(!result);

输出结果想反,真变假,假变真

表达式           !表达式

True             False

False            Ture

 

逻辑表达式关系表达式习题

     

1.张三的语文和数学成绩都大于90分

   Console.WriteLine("请输入你的语文成绩?:");

            int chinese = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("请输入你的数学成绩?");

            int math = Convert.ToInt32(Console.ReadLine());

            //张三的语文和数学成绩都大于90分

            bool first = chinese>90 && math>90;

            //语文和数学至少一门是大于90分的

            bool secend = chinese > 90 || math > 90;

            Console.WriteLine("\"张三的语文和数学成绩都大于90分\"这句话的结果为:{0}",first);

            Console.WriteLine("\"语文和数学至少一门是大于90分的\"这句话的结果为:{0}",secend);

            Console.ReadKey();
 

2.语文和数学有一门是大于90分的

            Console.WriteLine("请输入一个年份");

            int year = Convert.ToInt32(Console.ReadLine());

            bool real = (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0));

            Console.WriteLine(real);

 

            int a = 10;

            int b = 5;

            //bool result = ++a > 50 && ++b > 1; //  &&第一个为真才继续运算

            bool result = ++a > 5 || ++b > 1;    //  ||只要有一个为真就停止运算

            Console.WriteLine("a={0} b={1}", a, b);

if

if 结构的基本语法

if (条件)

  语句1;

执行过程:

首先判断条件的结果,如果田间为Ture,则执行语句1.如果条件为False,则跳过语句1.执行后面的语句.

注意:

1.if如果括号中的条件,要能计算成一个bool类型的值.

2.默认情况下,if语句只能带1句话.即和if语句有关系的语句只有1.

            //if语句基本用法

            int a = 3;

            if (a > 10)                      //这里没有;号

            Console.WriteLine("成立");       //if默认只带这一句话

            Console.WriteLine("程序结束");   //这句话和if没关系

if作业 

 

让用户输入年龄,如果输入的年龄大于18岁,则给用户显示你已成年.

            Console.WriteLine("请输入您的年龄");

            int age = Convert.ToInt32(Console.ReadLine());

            if (age >= 18)

            {

                Console.WriteLine("你已成年!");

            }

如果张三的语文成绩大于90并且音乐成绩大于80,或者语文成绩等于100并且音乐成绩大于70,则奖励100元

            Console.WriteLine("请输入你的语文成绩?");

            int chinese = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("请输入你的音乐成绩");

            int music = Convert.ToInt32(Console.ReadLine());

            if ((chinese >= 90) && (music >= 80) || (chinese == 100) && (music >= 70))

            {

                Console.WriteLine("奖励一百元!");

            }

让用户输入用户名和密码,如果用户名为admin,密码为myPass,则提示登陆成功

            Console.WriteLine("请输入您的用户名");

            string userName = Console.ReadLine();

            Console.WriteLine("请输入您的密码");

            string myPass = Console.ReadLine();

            if (userName == "admin" && myPass == "myPass")

            {

                Console.WriteLine("登陆成功");

            }
 

if-else
 

//如果张三的考试成绩大于(90)分,那么爸爸奖励他100元钱,否则的话,爸爸就让张三写学习总结.

            int score = 95;

            if (score >= 90)

            {

                Console.WriteLine("奖励100元");

            }

            if (score <= 90)

            {

                Console.WriteLine("不准出去玩,写总结去");

            }

            Console.ReadKey();

if-else 结构

语法:

if(条件)

{语句块1}

else

{语句快2}

执行过程:

如果条件为ture,则执行if带的语块1,并且跳过else带的语句块2

如果条件为false.则跳过if带的语句块1.执行else带的语句块2

            int score = 95;

            if (score >= 90)

            {

                Console.WriteLine("奖励100元");

            }

            else

            {

                Console.WriteLine("不准出去玩,写总结去");

            }

switch-case

提示用户输入年龄,如果大约等于18,则告知用户可以查看,如果小于10岁,则告知不允许查看,如果大

于等于10岁并且小于18,则提示用户是否继续查看(yes.no),如果输入的是yes则提示用户请查看,否则

提示"退出,你放弃查看"

            Console.WriteLine("你现在看的电影肯能涉及到血腥暴力,请输入你的年龄:");

            int age = Convert.ToInt32(Console.ReadLine());

            if (age >= 18)

            {

                Console.WriteLine("你可以观看");

            }

            else if (age >= 10)

            {

                Console.WriteLine("你确定要管看吗?请输入yes观看,其他则退出");

                string input = Console.ReadLine();

                if (input == "yes")

                {

                    Console.WriteLine("请观看");

                }

                else

                {

                    Console.WriteLine("你选择了退出!");

                }

            }

            else

            {

                Console.WriteLine("年龄太小不允许观看");

            }

            Console.ReadKey()

switch(语法)

switch (语句块)

{

case 值1:语句块1

break;

case 值2:语句块2

break;

default:语句块3

break;

}

例题

            Console.WriteLine("请输入你对力斯得评定等级(A-E)");

            string input = Console.ReadLine();

            decimal salary = 5000;

            bool flag = false;

            if (input == "A")

            {

                //salary=salary+500

                salary += 500;

            }

            else if (input == "B")

            {

                salary += 200;

            }

            else if (input == "C")

            {

            }

            else if (input == "D")

            {

                salary -= 200;

            }

            else if (input == "E")

            {

                salary -= 500;

            }

            else

            {

                Console.WriteLine("输入有误,只能输入大写ABCDE");

                flag = true;

            }

            if (flag == false)

            {

                Console.WriteLine("李四的工资为:" + salary);

            }
//用switch-case实现上面的功能

执行过程:首先计算表达式,然后根据计算结果与匹配case后面的值.如果有匹配项,则执行匹配后面的

语句,直到break语句跳出switch-case,如果所有的case值都不匹配,那么有defanlt则执行default后

面的语句,直到break结束,如果没有default.则跳出switch-case,什么都不执行.

default://注意,匹配时和位置没有关系,只和值有关系.

            Console.WriteLine("请输入你对李四的评定等级(A-E)");

            string input = Console.ReadLine();

            decimal salary = 5000;

            bool flag = false;

            switch (input)

            {

                case "A":

                    salary += 500;

                    break;

                case "B":

                    salary += 200;

                    break;

                case "C":

                    break;

                case "D":

                    salary -= 200;

                    break;

                case "E":

                    salary -= 500;

                    break;

                default://注意,匹配时和位置没有关系,只和值有关 系.

                    Console.WriteLine("你输入的有问题!");

                    flag = true;

                    break;

            }

                    if (flag == false)

                    {

                        Console.WriteLine("李四的工资为:" + salary);

                    }

           

            Console.ReadKey();

 

switch-case作业



switch:一般只能用于等值比较

if-else of:可以处理范围

1.请用户输入年份,输入月份,输出该月的天数

            Console.WriteLine("请输入年份");

            int year = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("请输入月份");

            int month = Convert.ToInt32(Console.ReadLine());

            switch (month)

            {

                case 1:

                case 3:

                case 5:

                case 7:

                case 8:

                case 10:

                case 12:

                    Console.WriteLine("31天");

                    break;

                case 2:

                    if (year % 4 == 0 || year % 400 == 0 && year % 100 != 0)

                    {

                        Console.WriteLine("29天");

                    }

                    else

                    {

                        Console.WriteLine("28天");

                    }

                    break;

                default:

                  Console.WriteLine("30天");

                   break;

              }

            Console.ReadKey();

2.对学员结业考试的成绩测评(改成Switch来做)

成绩>=90:A

90>成绩>=80:B

80>成绩>=70:C

70>成绩>=60:D

成绩<60:E

            Console.WriteLine("输入你的成绩");

            int score = Convert.ToInt32(Console.ReadLine());

            switch (score / 10)

            {

            case 9:

                    Console.WriteLine("A");

                    break;

            case 8:

                    Console.WriteLine("B");

                    break;

            case 7:

                    Console.WriteLine("C");

                    break;

            case 6:

                    Console.WriteLine("D");

                    break;

                default:

                    Console.WriteLine("E");

                    break;

                      

            }

            Console.ReadKey();
 

while



while循环的语法:

while(条件)                 //条件叫:循环条件

{

要循环执行的N条程序;        //循环体

}

执行过程:

1.先判断循环条件,如果条件为ture,则转向2,如果条件为false,则转向3

2.执行循环体,循环体执行完后,转向1

3.跳出循环,循环结束

            int i = 0;

            while (i < 5)

            {

                Console.WriteLine("下次考试一定要细心!");

                i++;

            }

            Console.ReadKey();

 

作业

1.打印100次"欢迎来到传播智客学习."

       int i = 0;

            while (i < 100)

            {

                Console.WriteLine("欢迎来到传播智客学习!");

                i++;

            }

            Console.ReadKey();

2.输入班级人数,然后依次输入学员成绩,计算班级学员的平均成绩和总成绩

            Console.WriteLine("请输入你们班有多少人?");

            int count=Convert.ToInt32(Console.ReadLine());

            int score=0;//存用户输入的分数

            int i=0;

            int sum = 0;//用于存总成绩

            while (i<count)

            {

                Console.WriteLine("请输入第{0}个学生的成绩",i+1);

                score = Convert.ToInt32(Console.ReadLine());

                sum = sum + score; //sum+=score;

                i++;

            }

            Console.WriteLine("本班共有{0}人,总成绩为{1}分,平均成绩为{2}分",count,sum,sum/count);

            Console.ReadKey();

3.老师问学生,这道题你会做了吗?如果学生答"会了(y)",则可以放学,如果学生不会做(n),则老师再讲一遍,再问学生是否会做了......

-知道学生会了为止,才可以放学.

-直到学生会或老师给他讲了10遍还不会,都要放学

            Console.WriteLine("这道题你会做了吗?(y/n)");

            string answer=Console.ReadLine();

            int i = 0;

            int b = 0;

            while(answer != "y" &&

                answer != "n"&&b<1)

            {

                Console.WriteLine("输入错误!请重新输入!这道题你会做了吗?(y/n)");

                answer = Console.ReadLine();

                b++;

            }

            while(answer=="n" && i<10)

            {
                Console.WriteLine("老师讲一遍题!");

                i++;

                Console.WriteLine("这道题你会做了吗?(y/n)");

                answer = Console.ReadLine();

            }

            Console.WriteLine("你可以放学了!");

            Console.ReadKey();

4.2006年培养了学院8万人,每年增长25%,请问按此增长速度,到哪一年培训学员的人数将达到20万人?

            int year = 2006;

            double stu = 80000;

            while(stu<=200000)

            {

                stu = stu * 1.25;   //计算人数增加25%的值

                year++;

            }

            Console.WriteLine("到{0}年后人数达到20万",year);

            Console.ReadKey();
 

do-while



do while

语法:

do

{循环体}

while(条件);

执行过程:

1.执行循环体,执行完循环体转向2

2.判断条件是否成立,如果条件为ture,则转向1.如果条件为false,则转向3

3.跳出循环,循环结束

假如循环提交一开始就不成立,对于while循环,一次都不会执行,对于to-while循环体一般至少会执行一次

while:先判断,后执行

do-while:先执行,后判断

            string answer;

            do

            {

                Console.WriteLine("小兰表演一遍舞蹈!");

                Console.WriteLine("老师你满意吗?(y/n)");

                answer = Console.ReadLine();

            }

            while (answer == "n");

            Console.WriteLine("跳得不错了,回家好好休息!");

            Console.ReadKey();

 
检测异常
try

{

}

catch

{

}

如果try中的代码没有出异常,则不会执行catch中的代码

如果try中的代码出现异常,则程序立即跳到catch中

            Console.WriteLine("请输入张三的分数?");

            try

            {

                int seore = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("in try");

            }

            catch

            {

                Console.WriteLine("in catch");

            }

            Console.ReadKey();

 

 

            string answer;

            do

            {

                Console.WriteLine("小兰表演一遍舞蹈!");

                Console.WriteLine("老师你满意吗?(y/n)");

                answer = Console.ReadLine();

                while (answer != "y" || answer != "n")

                {

                    Console.WriteLine("输入错误");

                }

            }

            while (answer == "n");

            Console.WriteLine("跳得不错了,回家好好休息!");

            Console.ReadKey();

 

//1.计算1到100之间的整数的和;

            int sum = 0;

            int i = 1;

            while (i <= 100)

            {

                sum = sum + i;

                i++;

            }
 

//2.要求用户输入用户名和密码,只要不是admin/888888,就一直提示用户名或密码错误,请重新输入

            string userNmae;

            string password;

            bool flag=false;

            do

            {

                Console.WriteLine("请输入用户名?");

                userNmae = Console.ReadLine();

                Console.WriteLine("请输入密码");

                password = Console.ReadLine();

                if (userNmae != "admin" || password != "88888")

                {
                    Console.WriteLine("用户名或密码错误,请重新输入!");

                    flag = true;

                }

            } while (flag);

            Console.WriteLine("登陆成功!");

//3.不断要求用户输入学生姓名,输入q结束

            string input;

            do

            {

                Console.WriteLine("请输入用户姓名?");

                input = Console.ReadLine();

            } while (input != "q");

            Console.WriteLine("程序结束.");
          

//4.不断要求用户输入一个数字,然后打印这个数字的二倍,当用户输入q的时候程序结束

            int input;

            bool flag = false;

            {

                try

                {

                    Console.WriteLine("请输入一个数字");

                    input = Convert.ToInt32(Console.ReadLine());

                    Console.WriteLine("{0}的两倍是{1}", input, input * 2);

                    flag = true;             

                }

                catch

                {

                    flag = false;

                }

            }while(flag)

 

 

            string input;

            int number;

            Console.WriteLine("请出入一个数字(q结束)");

            input = Console.ReadLine();

            while (input != "q")

            {

                number=Convert.ToInt32(input);

                Console.WriteLine("{0}的两倍是{1}",number,number*2);

           

                Console.WriteLine("请出入一个数字(q结束)");

                input = Console.ReadLine();

            }

//5.不断要求用户输入一个数字(假定用户输入的都是正整数),当用户输入end的时候显示刚才输入

的数字中的最大值

            int max = 0;

            string input="";

            int number;

            do

            {

                try

                {

                    Console.WriteLine("请输入一个数?");

                    input = Console.ReadLine();

                    number=Convert.ToInt32(input);

                    if(number>max)

                    {

                        max = number;

                    }

                }

                catch

                {

                    if (input!="end")

                    {

                        Console.WriteLine("输入了非法数据!");

                        input = "end";

                    }

                }

               

            }while(input!="end");

            Console.WriteLine("你输入的最大值是"+max);

            Console.ReadKey();

调试

设置断点

单步运行

观察变量

 

For循环
语法:

for(表达式1;表达式2;表达式3;)

{

循环体

}

执行过程:

第1步 计算表达式1,转向第2步

第2步 计算表达式2(循环条件),如果表达式2的值为ture转向第3步.如果表达式2的值为false,转向第步

第3步 执行循环体,转向第4步

第4步 执行表达式3,转向第2步

第5步 循环结束

            int i = 0;   //相当于表达式1

            while (i < 100) //循环条件,相当于表达式2

            {

                Console.WriteLine("下次我一定细心!");

                i++;//相当于表达式3

            }

一般情况下,表达式1用于定义循环变量和对循环变量赋初值

表达式2:循环条件

表达式3:用于改变循环变量的值

            for (int i = 0; i < 100; i++)

            {

                Console.WriteLine("下次我一定要细心!"+i);

            }

 

1.求1-100间的所有偶数和?

            int sum = 0;

            for (int i = 1; i <= 100; i++)

            {

                if (i % 2 == 0)

                {

                    sum = sum + i;

                }

            }

            Console.WriteLine("1-100的所有偶数" + sum);

            Console.ReadKey();

2.找出100-999间的水仙花数?

            for (int i = 100; i <= 999; i++)

            {

                int ge = i % 10;

                int shi = i / 10 % 10;

                int bai = i / 100;

                if (i == ge * ge * ge + shi * shi * shi + bai * bai * bai)

                {

                    Console.WriteLine(i);

                }

               

            }

*死循环

            for (; ; )

            {

                Console.WriteLine("死循环!");

            }

 

 

1.输出九九乘法表(长方形)

            for(int i = 1;i<=9;i++)

            {

                for (int a = 1; a <=9; a++)

                {

                    Console.Write("{0}X{1}={2:00}  ",i,a,i*a);

                }

                Console.WriteLine();

            }
2.输出九九乘法表(三角形)

            for(int i = 1;i<=9;i++)

            {

                for (int a = 1; a <=i; a++)

                {

                    Console.Write("{0}X{1}={2:00}  ",i,a,i*a);

                }

                Console.WriteLine();

            }
3.根据6可以输出一下加法表:

0+6=6

1+5=6

2+4=6

3+3=6

4+2=6

5+1=6

6+0=6

            Console.WriteLine("请输入一个值!");

            bool flag = false;

            int a = 0;

            while (flag == false)

            {

                try

                {

                    a = Convert.ToInt32(Console.ReadLine());

                    flag = true;

                }

                catch

                {

                    Console.WriteLine("你刚刚输入的不是数字");

                    flag = false;

                }

            }

            for (int b = 0; b <= a; b++)

            {

                Console.WriteLine("{0}+{1}={2}", b, a - b, a);

            }

            Console.ReadKey();

*判断输入的是否为数字

            Console.WriteLine("请输入一个值");

            bool flag = false;

            int a = 0;

            while (flag == false)

            {

                try

                {

                    a = Convert.ToInt32(Console.ReadLine());

                    flag = true;

                }

                catch

                {

                    Console.WriteLine("你输入的有误,请重新输入");

                    flag = false;

                }

            }

            Console.WriteLine("你刚才输入的值是:{0}", a);

            Console.ReadKey();

 

breakcontinue



//练习1.循环录入5个人的年龄并计算平均年龄,如果录入的数据出现负数或大于100的数,立刻停止输入并报错

            int age = 0;

            int sum = 0;

            for (int i = 0; i < 5; i++)

            {

                Console.WriteLine("请输入第{0}个人的年龄", i + 1);

                try

                {

                    age = Convert.ToInt32(Console.ReadLine());

                    if (age < 0 || age >= 100)

                    {

                        Console.WriteLine("年龄不合法!");

                        break;

                    }

                    sum = sum + age;

                }

                catch

                {

                    Console.WriteLine("你输入的不是数字,程序终止!");

                    break;

                }

            }

            Console.WriteLine("这五个人的平均年龄是{0}", sum / 5);

            Console.ReadKey();

//练习2:在while中用break实现要求用户一直输入用户名和密码,只要不是admin/888888就一直提示要求重新输入,如果正确则提登陆成功.

            string userName, passWord;

            while (true)

            {

                Console.WriteLine("请输入用户名");

                userName = Console.ReadLine();

                Console.WriteLine("请输入密码");

                passWord = Console.ReadLine();

                if (userName == "admin" && passWord == "888888")

                {

                    break;

                }

                Console.WriteLine("你输入的用户名或密码错误,请重新输入!");

            }

            Console.WriteLine("登陆成功");

            Console.ReadKey();
//练习3:1-100之间的整数相加,得到累加值大于20的当前数

            int sum=0;

            int i = 0;

            for (i = 1; i <= 100; i++)

            {

                sum += i;

                if (sum>=20)

                {

                    break;

                }

            }

            Console.WriteLine(i);

         

            Console.ReadKey();
          
break:
1.可以用于switch-case判断中,用于跳出switch

2.用在循环中,用于立即跳出(终止)循环

注意:用于循环中,跳出的是break所在的循环
continue

用于循环中,程序一旦执行到continue语句,立即结束本次循环(就是不再执行循环体中的continue下面的语句),直接进行下一次循环.(do-while/while直接进行下一次循环条件的判断.如果条件成立.则再次进入循环.对于for循环,先执行表达式三,再判断循环条件是否成立!)

//练习一:用while continue实现计算1到100之间的除了能被7整除之外所有整数的和.

            int i = 0;

            int sum = 0;

            while (i <= 100)

            {

                i++;

                if (i % 7 == 0)

                {

                    sum = i + sum;

                }

            }

            Console.WriteLine("和为{0}",sum);

            Console.ReadKey();

            int i = 0;

            int sum = 0;

            while (i<100)

            {

               

                if (i % 7 == 0)

                {

                    i++;

                    continue;

                }

                sum = i + sum;

                i++;

            }

            Console.WriteLine("和为{0}", sum);

            Console.ReadKey();

三元表达式

表1?表2:表3

执行过程:首先计算表达式1,表达式1应该是一个能够计算成bool类型的值,如果表达式1的值为true,则表达式2的值作为整个表达式的值,如果表1的值为false,则表达式3的值做为整个表达式的值.

表达式2和表达式3的类型一定要相同(相兼)

            int a = 10;

            int b = 20;

            if (a > b)

            {

                Console.WriteLine(a);

            }

            else

            {

                Console.WriteLine(b);

            }

            int max = a > b ? a : b;

            Console.WriteLine(max);

            Console.WriteLine(a > b ? a : b);

            Console.ReadKey();

顺序结构:语句顺序执行

分支结构:语句在满足条件下执行
if,if-else,switch-case,表1?表2:表3

循环结构:语句在满足条件下循环执行多次

while,do-while,for

跳转语句

brak,continue,goto

goto语法

goto 标签

标签:

            goto myLabel;

            Console.WriteLine("a");

            Console.WriteLine("b");

            myLabel:

            Console.WriteLine("c");

            Console.ReadKey();

 

常量枚举

常量:
语法:

const 类型 常量名 = 常量值

在定义时赋值,在其他地方不允许赋值

            const double PI = 3.14;

            Console.ReadKey();

枚举:

让我们定义一种枚举类型并且在定义这种类型时,我们要制定这个类型的所有值

语法:

enum 自己起的;类型名称{值1,值2,值3....值n};

枚举的定义,一般和类定义在同一个级别,这样,在同一个命名空间下的类就都可以使用这个枚举了

    enum Gender

    {

    男,

    女

    }

枚举的作用:

1.限制用户不能随意复赋值,只能在定义枚举时列举的值中选择

2.不需要死记每个值是什么,只需要选择相应的值

注意:定义枚举时,值不能是int类型

枚举类型的变量都可以强制转换成一个int类型

枚举的值在定义时是有一个默认编号的,编号从0开始.

            Gender sex;

            sex = Gender.男;

            Console.WriteLine((int)sex);

            Console.ReadKey();

如果把一个字符串转换成枚举类型:

(自枚)(Enum.Parse(typeof(自枚),"带转换的字符")

 

结构

为什么要用结构:

1.比如我们上课讲的为了存储一个人的信息,要声明一组变量,当我们要存储N个人的信息时,就要申明n组变量,麻烦

2.存储一个人信息的这几个变量间没有关系,容易记乱语法:

访问修饰符 struct 结构名

{

定义结构成员

}

    enum Gender

    {

        男,

        女,

    }

    public struct person    //定义了一个叫Person的结构

    {

        public string name; //结构的成员

        public Gender sex;  //结构的成员

        public int age;     //结构的成员

    }

    class Program

    {

        static void Main(string[] args)

        {

            person onePerson;

            onePerson.name = "zhangsan";

            onePerson.age = 20;

            onePerson.sex = Gender.男;

            Console.WriteLine("我叫{0},我今年{1},我是{2}             性",onePerson.name,onePerson.age,onePerson.sex);

            person secPerson;

            secPerson.name = "lisi";

            secPerson.age = 26;

            secPerson.sex = Gender.男;

            Console.WriteLine("我叫{0},我今年{1},我是{2}性",secPerson.name,secPerson.age,secPerson.sex);

            Console.ReadKey();



0计算机中最小的单位叫"位",bit,比特

就把8个二进制位分成一组,那么8个二进制位叫做 字节

Byte B 计算机能够处理的最小的单位

1KB=1024B

1MB=1024KB

1GB=1024MB

           

//练习1.从一个整数组中取出最大值和最小值,计算一个整数数组的所有元素的和

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

            int max = 0;

            int min = 0;

            int sum = 0;

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

            {

                if (number[i] > max)

                {

                    max = number[i];

                }

                if (number[i] < min)

                {

                    min = number[i];

                }

                sum += number[i];

            }

            Console.WriteLine("最大值为{0},最小值为{1},和为{2}", max, min,sum);

            Console.ReadKey();
//练习3.将字符串数组输出为|分割的形式,比如"梅西|卡卡|郑大世"

(1)         string[] name = { "梅西", "卡卡", "郑大世" };

            string str = "";

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

            {

                str = str + name[i] + "|";

            }

            Console.WriteLine(str);

            Console.ReadKey();

(2)         string[] name = { "梅西", "卡卡", "郑大世" };

            string str = "";

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

            {

                if (i == name.Length - 1)

                {

                    str = str + name[i];

                }

                else

                {

                    str = str + name[i] + "|";

                }

            }

            Console.WriteLine(str);

            Console.ReadKey();
//练习4.讲一个整数数组的每一个元素进行如下的处理:如果元素是正数则将这个位置的元素的值加1,如果元素是负数则将这个位置的元素的值减1,如果元素是0,则值不变

            string[] name = { "梅西", "卡卡", "郑大世" };

            for (int i = name.Length-1; i >= 0; i--)

            {

                Console.WriteLine(name[i]);

            }

            Console.ReadKey();
//练习5:将一个字符串数组的元素顺序进行反转{"3","a""8","haha"}{"haha","8","a","3"}.第i个和第Length-i-1个进行交换

            string[] name = { "梅西", "卡卡", "郑大世" };

            string temp;

            for (int i = 0; i < name.Length / 2; i++)

            {

                //交换第i个与第length-i个

                temp = name[i];

                name[i] = name[name.Length - 1 - i];

                name[name.Length - 1 - i] = temp;

            }

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

            {

                Console.WriteLine(name[i]);

            }

            Console.ReadKey();

  Console.Clear(); 清屏
 

 

作业

//练习1.从一个整数组中取出最大值和最小值,计算一个整数数组的所有元素的和

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

            int max = 0;

            int min = 0;

            int sum = 0;

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

            {

                if (number[i] > max)

                {

                    max = number[i];

                }

                if (number[i] < min)

                {

                    min = number[i];

                }

                sum += number[i];

            }

            Console.WriteLine("最大值为{0},最小值为{1},和为{2}", max, min,sum);

            Console.ReadKey();
//练习3.将字符串数组输出为|分割的形式,比如"梅西|卡卡|郑大世"

(1)         string[] name = { "梅西", "卡卡", "郑大世" };

            string str = "";

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

            {

                str = str + name[i] + "|";

            }

            Console.WriteLine(str);

            Console.ReadKey();

(2)         string[] name = { "梅西", "卡卡", "郑大世" };

            string str = "";

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

            {

                if (i == name.Length - 1)

                {

                    str = str + name[i];

                }

                else

                {

                    str = str + name[i] + "|";

                }

            }

            Console.WriteLine(str);

            Console.ReadKey();

//练习4.讲一个整数数组的每一个元素进行如下的处理:如果元素是正数则将这个位置的元素的值加1,如果元素是负数则将这个位置的元素的值减1,如果元素是0,则值不变

            string[] name = { "梅西", "卡卡", "郑大世" };

            for (int i = name.Length-1; i >= 0; i--)

            {

                Console.WriteLine(name[i]);

            }

            Console.ReadKey();
//练习5:将一个字符串数组的元素顺序进行反转{"3","a""8","haha"}{"haha","8","a","3"}.第i个和第Length-i-1个进行交换

            string[] name = { "梅西", "卡卡", "郑大世" };

            string temp;

            for (int i = 0; i < name.Length / 2; i++)

            {

                //交换第i个与第length-i个

                temp = name[i];

                name[i] = name[name.Length - 1 - i];

                name[name.Length - 1 - i] = temp;

            }

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

            {

                Console.WriteLine(name[i]);

            }

            Console.ReadKey();
 

ReadInt


            Console.WriteLine("请输入你的年龄?");

            int age = Readint();

            Console.WriteLine("你刚刚输入的年龄为"+age);

            Console.WriteLine("请输入你是哪一年出生的?");

            int year = Readint();

            Console.WriteLine("哦!你是{0}年出生的啊!",year);

            Console.WriteLine("请输入你们班级有多少人?");

            int count = Readint();

            Console.WriteLine("你们班有{0}个人.",count);

            Console.ReadLine();

        }

            public static int Readint()

            {

            int number = 0;

            do

            {

                try

                {

                    number = Convert.ToInt32(Console.ReadLine());

                    return number;

                }

                catch

                {

                    Console.WriteLine("输入有误,请重新输入!");

                }

            }

            while (true);

 

冒泡排序
 

在一个循环中,第i个元素与第length-1-i个元素进行交换

冒泡排序:

让数组中的元素两两比较(第i个与第i+1个比较),经过n(i-1)遍两两比较,数组中的元素能按照我们预期的的规律排序.

要从大到小排序,我们进行两两比较的时候用<

(从大到小用<,从小到大用>)

N个数需要排n-1趟

第t趟比较的次数为:n-t次

i=0 第一趟

i=1 第二趟

趟数:i+1   t=i+1

For(int i = 0;i>n-1;i++)   

{

   for(int j = 0;j<n-i-1;j++)

   {

      int c=a;

      a=b;

      b=c

   }

}

            int[] score = { 18, 20, 48, 76, 20, 38, 87, 90, 37, 45, 65, 65, 14, 67, 95 };

            for (int i = 0; i > score.Length - 1; i++)

            {

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

                {

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

                    {

                        int temp = score[j];

                        score[j] = score[j + 1];

                        score[j + 1] = score[j];

                    }

                }

            }

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

            {

                Console.WriteLine(score[i]);

            }

                Console.ReadKey();
 

方法



函数就是将一堆代码进行重用的一种机制.函数就是一段代码,这段代码可能有输入的值(参数),可能会返回值.一个函数就像一个专门做这件事的人,我们调用它来做一些事情,它可能需要我们提供一些数据给它,它执行完成后可能会有一些执行结果给我们.要求的数据就叫做参数,返回的执行结果就是返回值.

String s = Console.ReadLine()就是一个有返回结果的函数;

Console.WriteLine("hello")就是一个执行参数的函数,只有告诉WriteLine被打印的数据它才知道如何打印;int i=COnvert.Toint32("22")则是一个既有参数又有返回值的函数.

有了函数写代码就像拼积木,C#中的各种各样的技术其实就是通过for、if等这些基础的语法将不同的函数按照一定的逻辑组织起来.

方法

定义:

[访问修饰符][static]返回值类型 方法名()

{

方法体;

}

命名规则:方法名开头大写,参数名开头小写,参数名,变量名要有意义

方法的调用,对于静态方法,如果在同一个类中,直接写名字调用就行了

return可以立即退出方法

功能:用来复用代码.当我们在一个程序中反复的写了同样的代码.那一般情况下,我们可以把需要重复写的代码定义在一个方法中,用的时候只需要调用就行了.

定义方法的语句:

[访问修饰符][static]返回值类型 方法名()

{

 方法体

}

        static void Main(string[] args)

        {

            ShowUI();

            Console.WriteLine("谢谢使用,按任意键退出!");

            Console.ReadKey();

        }

        /// <summary>

        /// 用于显示软件主界面的方法

        /// </summary>

        public static void ShowUI()

        {

            Console.WriteLine("**********************************");

            Console.WriteLine("*     欢 迎 您 使 用 本 软 件    *");

            Console.WriteLine("**********************************");

        }
  

参数
  

注意:

1.方法一般要定义在类中

2.如果方法没有返回值,则返回值类型写void

2.如果方法没有参数,()不能省略

方法的调用:如果是静态方法(由static修饰的)则使用类名.方法名().

在类中调用本调的方法,可以只写方法名();

 

求两个整数的和

        static void Main(string[] args)

        {

            Add(3,6);

            Console.ReadKey();

        }

        public static void Add(int a, int b)

        {

            Console.WriteLine("a+b={0}",a+b);

        }

int.Parse(string)       转类型

在方法名后面的括号内定义变量,叫做定义这个方法的参数.这里定义的变量用于接受调用者传过来的数据

注意:如果一个方法一旦有参数,那么调用者就必须传参数,并且传参数的个数与对应位置上的类型必须一致

        static void Main(string[] args)

        {

            int a = 3;

            Text(a);

            Console.WriteLine(a);

            Console.ReadKey();

        }

        //被调用者

        public static void Text(int a)  

        {

            a = a + 3;

            Console.WriteLine(a);

        }

求两个整数的和

        static void Main(string[] args)

        {

            Add(3,6);

            Console.ReadKey();

        }

        public static void Add(int a, int b)

        {

            Console.WriteLine("a+b={0}",a+b);

        }
 

返回值



当调用者想访问我们方法中的变量时,可以通过返回值返回.

例如:

string s=Console.ReadLine()

int i= Convert.ToInt("22")

为什么方法前面能定义一个变量接受方法的值,是因为方法中使用了返回值

只要在方法中返回了值,那么在调用方法是,前面就应该用一个变量来接受方法的返回值

为什么使用返回值?因为变量规定了类型而不再是隐性

注意:一个方法只能有一个返回值

一旦一个方法有返回值,那注在这个方法值中,就必须通过rerurn语句返回一个值,并且这个值要与返回值类型是同样的

语法:

return result;

        static void Main(string[] args)

        {

            Console.WriteLine("你确定要关机?(y/n)");

            string s=ReadAnswer();

            //在main方法中,我能知道用户输入的是y还是n吗?

            if(s=="y")

            {

                Console.WriteLine("用户正在关机...");

            }

            else

            {

                Console.WriteLine("用户还没有关机...");

            }

            Console.ReadKey();

        }

        public static string ReadAnswer()

        {

            string result = "";

            do

            {

                result = Console.ReadLine();

                if (result != "y" && result != "n")

                {

                    Console.WriteLine("输入有误,请重新输入");

                }

            } while (result != "y" && result != "n");

            //当方法执行完成后,result中存储的就是用户存储的y或n

            return result;

        }
 

两个数求和(规定为int (有返回值)):

        static void Main(string[] args)

        {

            Console.WriteLine("请输入第一个数!");

            int a = int.Parse(Console.ReadLine());

            Console.WriteLine("请输入第二个数!");

            int b = int.Parse(Console.ReadLine());

            int sum = Add(a, b);

            Console.WriteLine("平均值为:{0}", sum / 2);

            Console.ReadKey();

        }

        public static int Add(int a, int b)

        {

            return a + b;

        }

返回值查看是否为闰年.

        static void Main(string[] args)

        {

            Console.WriteLine("请输入年份!");

            int year = Convert.ToInt32(Console.ReadLine());

            bool result = LeapYear(year);

            if (result)

            {

                Console.WriteLine("闰年");

            }

            else

            {

                Console.WriteLine("不是闰年");

            }

            Console.ReadKey();

        }

        public static bool LeapYear(int year)

        {

            if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0)

            {

                return true;

            }

            else

            {

                return false;

            }

        }

 

 一个变量一旦定义在方法外,类的里面,就叫做类的字段,这个变量就可以被本类的所有方法所访问,但是要注意,静态方法只能访问静态字段.

        static void Main(string[] args)

        {

            int max = Max(10, 20);

            Console.WriteLine(max);

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

            int result = Sum(n);

            Console.WriteLine(result);

            Console.ReadLine();

        }

        public static int Sum(int[] numbers)

        {

            int numberSum = 0;

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

            {

                numberSum += numbers[i];

            }

            return numberSum;

        }

        /// <summary>

        /// 本方法用于找出两个数中最大的数

        /// </summary>

        /// <param name="i1">第一个数</param>

        /// <param name="i2">第二个数</param>

        /// <returns></returns>

        public static int Max(int i1, int i2)

        {

            if (i1 > i2)

            {

                return i1;

            }

            else

            {

                return i2;

            }

        }

 

outref



由const修饰的常量不能定义静态

什么叫方法的重载:

一般在同一个类型中,方法名想通,并且方法的参数的个数不同或者对应位置上的类型不同,才能构成方法的重载

实现步骤:

1.在方法的参数类型前面加out,那么传参数的时候,也必须在number钱加out表明这个参数不是传入的,而是i用来传出值的

2.如果参数是以out形式传入的,那么在传入前可以不赋初值.

3.在方法中对于由out修饰的参数,必须赋值,并且必须在使用前赋值

        static void Main(string[] args)

        {

            string s = "123";

            int re;

            if (int.TryParse(s, out re) == true)

            {

                Console.WriteLine("能转换成功,转换后的数字为:" + re);

            }

            else

            {

                Console.WriteLine("转换失败");

            }

            Console.ReadKey();
练习:写一个MyTryParse方法,要求用户传入一个字符串,如果这个字符串能转换成int类型,则方法返回ture,并且转换后的int类型数据通过方法的参数传出.如果字符串不能转换成int类型,则方法返回false,那么out传出的参数将没有意思,在方法中随意赋值就行.

        static void Main(string[] args)

        {

            string s = "123";

            int re;

            if (IntTryParse(s, out re))

            {

                Console.WriteLine("转换成功!" + re);

            }

            else

            {

                Console.WriteLine("转换失败!");

            }

            Console.ReadKey();

        }

        static bool IntTryParse(string s, out int result)

        {

            result = 0;

            try

            {

                result = Convert.ToInt32(s);

                return true;

            }

            catch

            {

                return false;

            }

        }

写一个方法,计算一个int类型数组中的每一元素的总和,和最大值与最小值?

  static void Main(string[] args)

        {

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

            int max, min, sum;

            sum = compute(nums, out max, out min);

            Console.WriteLine("数组的和为{0},最大值为{1},最小值为{2}",sum,max,min);

            Console.ReadKey();

        }

        static int compute(int[] numbers, out int max, out int min)

        {

            int sum = 0;

            max = numbers[0];

            min = numbers[0];

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

            {

                sum += numbers[i];

                if (numbers[i] > max)

                {

                    max = numbers[i];

                }

                if (numbers[i] < min)

                {

                    min = numbers[i];

                }

            }

            return sum;

        }
out用于传出值,大方法中必须对out修饰的传数进行赋值

ref双向,既可以传入,也可以传出

字啊传参数的过程中,如果参数有out或ref修饰的话,那么改变方法中的参数变量的值,调用者方法中变量的值也会相应改变

 

重复让用户输入一个数,判断该数是否是质数,输入q结束?

        static void Main(string[] args)

        {

            string input = "";

            int number = 0;

            bool result;

            do

            {

                Console.WriteLine("请输入一个正整数?");

                input = Console.ReadLine();

                if (input == "q")

                {

                    Console.WriteLine("程序结束!");

                    break;

                }

                try

                {

                    number = Convert.ToInt32(input);

                    result = zhishu(number);

                    if (result == true)

                    {

                        Console.WriteLine("{0}是质数", number);

                    }

                    else

                    {

                        Console.WriteLine("{0}不是质数", number);

                    }

                }

                catch

                {

                    Console.WriteLine("输入的数据有误,请重新输入!");

                    continue;

                }

            }

            while (true);

            Console.ReadKey();

        }

        /// <summary>

        /// 判断一个数是否为质数

        /// </summary>

        /// <param name="number"></param>

        /// <returns></returns>

        public static bool zhishu(int number)

        {

            for (int i = 2; i < number; i++)

            {

                //i能不能等于number

                if (number % 1 == 0)

                {

                    //上面的条件一旦成立,2到本身-1之间的数就除尽了,所以不是质数,返回false

                    return false;

                }

            }
            //循环执行完毕,也就说明上面的条件 number % i == 0 都不成立.说明是一个质数

            return true;

 

将一个字符串组输出为|分割的形式,比如"梅西|卡卡|郑大世"(用方法来实现此功能)

        public static string ConString(string[]names)

        {

            string result = "";

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

            {

                if (i == names.Length - 1)

                {

                    result += names[i];

                }

                else

                {

                    result += names[i] + "|";

                }

                }

            return result;

       

        }

        static void Main(string[] args)

        {

        string[] names = {"张三","李四","王五" };

        string str = ConString(names);

        Console.WriteLine(str);

        Console.ReadKey();

        }

 

------- Windows Phone 7手机开发.Net培训、期待与您交流! ------- 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐