文档库 最新最全的文档下载
当前位置:文档库 › 经典C#编程例子

经典C#编程例子

经典C#编程例子
经典C#编程例子

//(1)开发控制台应用程序,实现一个欢迎界面的功能。

//首先程序提示用户输入姓名,然后显示“欢迎XXX进入C#的世界”。

//最后显示一段鼓励的话,如“A ZA A ZA Fighting!”。

using System;

using System.Collections.Generic;

using System.Text;

namespace exercise1

{

class Program

{

staticvoid Main(string[] args)

{

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

string s = Console.ReadLine();

Console.WriteLine("欢迎" + s + "进入C#的世界!");

Console.WriteLine("A ZA A ZA Fighting!");

}

<2>

//(2)已知两个矩形的长和宽,编程求它们的面积和周长。

//假设,矩形1的长和宽分别为50和20;矩形2的长和宽分别为5.6和4.5。

//长、宽由键盘输入。

using System;

using System.Collections.Generic;

using System.Text;

namespace exercise2

{

class Program

{

staticvoid Main(string[] args)

{

Console.WriteLine("请输入第1个矩形的长和宽:");

float a1 = Convert.ToSingle(Console.ReadLine());

float b1 = Convert.ToSingle(Console.ReadLine());

Console.WriteLine("请输入第2个矩形的长和宽:");

float a2 = Convert.ToSingle(Console.ReadLine());

float b2 = Convert.ToSingle(Console.ReadLine());

Console.WriteLine("第1个矩形的周长是{0},面积是{1}", 2 * (a1 + b1), a1 * b1); Console.WriteLine("第2个矩形的周长是{0},面积是{1}", 2 * (a2 + b2), a2 * b2); }

}

//(3)写出一个控制台应用程序,实现一个string类型变量转换为一个int类型变量的多种方法。

using System;

using System.Collections.Generic;

using System.Text;

namespace exercise3

{

class Program

{

staticvoid Main(string[] args)

{

string s = Console.ReadLine();

int i = Convert.ToInt32(s); //第1种方法

int j = Int32.Parse(s); //第2种方法

Console .WriteLine ("{0},{1}",i,j);

}

}

}

<4>

//(4)编写一个控制台程序,将用户输入的以秒为单位计算的时间长度拆分为以时、分、秒计量,并输出。using System;

using System.Collections.Generic;

using System.Text;

namespace exercise4

{

class Program

{

staticvoid Main(string[] args)

{

int t = Int32.Parse(Console.ReadLine());

int h = t /3600;

int m = t % 3600 / 60;

int s = t % 60;

Console.WriteLine(t + "秒转换为:");

Console.WriteLine("{0}小时{1}分{2}秒", h, m, s);

}

}

<5>

//(2)编写程序,输出100以内个位数为6且能被3整除的所有的数。

using System;

using System.Collections.Generic;

using System.Text;

namespace exercise

class Program

{

staticvoid Main(string[] args)

{

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

if ((i % 10 == 6) && (i % 3 == 0))

Console.WriteLine(i);

}

}

}

<6>

//(1)编写程序,使用if语句将输入的三个整数按从小到大的顺序排序。

using System;

using System.Collections.Generic;

using System.Text;

namespace exercise1

{

class Program

{

staticvoid Main(string[] args)

{

Console.WriteLine("请输入三个整数:");

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

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

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

int t;

if (a > b)

{

t = a; a = b; b = t;

}

if (b > c)

{

t = b; b = c; c = t;

}

if (a> b)

{

t = a; a = b; b = t;

}

Console.WriteLine("排序后为:{0},{1},{2}", a, b, c);

}

}

<7>

//(3)编写一个简单的计算器程序,能够根据用户从键盘输入的运算指令和整数,进行简单的加减乘除运算。

using System;

using System.Collections.Generic;

using System.Text;

namespace exercise3

{

class Program

{

staticvoid Main(string[] args)

{

Console.WriteLine("请输入两个运算数字:");

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

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

Console.WriteLine("请输入运算符号:");

char s = Convert .ToChar (Console .ReadLine());

switch (s)

{

case'+': Console.WriteLine(a + "+" + b + "={0}", a + b); break;

case'-': Console.WriteLine(a + "-" + b + "={0}", a - b); break;

case'*': Console.WriteLine(a + "*" + b + "={0}", a * b); break;

case'/': Console.WriteLine(a + "/" + b + "={0}", (Single )a / b); break;

default: Console.WriteLine("输入的运算符有误!"); break;

}

}

}

}

<8>

using System;

using System.Collections.Generic;

using System.Text;

//(4)合数就是非素数,即除了1和它本身之外还有其他约数的正整数。

//编写一个程序求出指定数据范围(假设10~100)内的所有合数。

namespace exercise4

{

class Program

{

staticvoid Main(string[] args)

{

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

for(int j =2;j

if (i % j == 0)

{

Console.Write(i);

Console.Write(" ");

break;

}

}

}

}

<9>

//(1)定义两个方法,分别求两个正整数的最大公约数和最小公倍数。

//其中,最大公约数的计算采用辗转相除法;最小公倍数的计算采用先计算最大公约数,//然后再用两个数的积去除最大公约数来求得。

//在Main方法中实现两个待求正整数的输入及结果的输出。

using System;

using System.Collections.Generic;

using System.Text;

namespace exercise1

{

class Program

{

staticvoid Main(string[] args)

{

Console.WriteLine("请输入两个正整数:");

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

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

Console.WriteLine("最大公约数是:{0}" , gcd(i, j));

Console.WriteLine("最小公倍数是:{0}" , gcm(i, j));

}

publicstaticint gcd(int a, int b)

{

int max = a > b ? a : b;

int r = a % b;

while (r != 0)

{

a = b;

b = r; r = a % b;

}

return b;

}

publicstaticint gcm(int a, int b)

{

return a * b / gcd(a, b);

}

}

<10>

using System;

using System.Collections.Generic;

using System.Text;

//(2)定义一个方法,给三个整数按从小到大的顺序排序并求其和及平均值。

//其中,三个待求整数及其排序后的结果由引用参数传递;其和由输出参数传递;//平均值由返回值返回。在Main方法中实现三个待求整数的输入及结果的输出。namespace exercise2

{

class Program

{

staticvoid Main(string[] args)

{

int s=0;

Console.WriteLine("请输入3个正整数:");

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

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

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

Console.WriteLine("平均值为:"+function(ref a, ref b, ref c,out s)); Console.WriteLine("排序后:{0},{1},{2}", a, b, c);

Console.WriteLine("和为:"+s);

}

publicstaticdouble function(refint i, refint j, refint k, outint sum) {

int t;

if (i > j)

{

t = i; i = j; j = t;

}

if(j>k)

{

t = j; j = k; k = t;

}

if (i > j)

{

t = i; i = j; j = t;

}

sum = i + j + k;

return (i + j + k) / 3.0;

}

}

<11>

//(3)用重载方法实现两个整数或三个浮点数的排序,

//按照从小到大的顺序将排序结果输出。

using System;

using System.Collections.Generic;

using System.Text;

namespace exercise3

{

class Program

{

staticvoid Main(string[] args)

{

Console.WriteLine("请输入两个正整数:");

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

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

sort(ref a,ref b);

Console.WriteLine("排序后:{0},{1}", a, b);

Console.WriteLine("请输入3个浮点数:");

float x = Convert.ToSingle (Console.ReadLine());

float y = Convert.ToSingle(Console.ReadLine());

float z = Convert.ToSingle(Console.ReadLine());

sort(ref x, ref y, ref z);

Console.WriteLine("排序后:{0},{1},{2}", x, y, z);

}

publicstaticvoid sort(refint i, refint j)

{

if (i > j)

{

int t = i; i = j; j = t;

}

}

publicstaticvoid sort(reffloat i, reffloat j, reffloat k) {

float t;

if (i > j)

{

t = i; i = j; j = t;

}

if (j > k)

{

t = j; j = k; k = t;

}

if (i > j)

{

t = i; i = j; j = t;

}

}

}

}

<12>

//(6)创建一个类,它存储一个int数据成员MyNumber, //并给该数据成员创建属性。当该数据成员被存储时,//将其乘以100;当其被读取时,将其除以100。

using System;

using System.Collections.Generic;

using System.Text;

namespace exercise

{

class Program

{

staticvoid Main(string[] args)

{

Test t = new Test();

t.Number = 11;

Console.WriteLine(t.Number);

}

}

class Test

{

privateint MyNumber;

publicint Number

{

get { return MyNumber / 100; }

set { MyNumber = value * 100; }

}

}

}

<13>

//(1)在控制台应用程序中创建student类,并声明构造函数及构造函数的重载。

//要求类定义中包含字段:学号(字符串),姓名(字符串),年龄(整型)和性别(布尔型)。//输出性别时,根据对应的布尔值,输出“男”或“女”。

//要求:使用字段时可声明为公有,可以不使用属性。

//声明三种不同的构造函数,包括:①可初始化学号、姓名、性别与年龄字段值的构造函数;

//②只初始化姓名的构造函数;③声明默认的无参构造函数。

//实现用不同的初始化方式来声明3个不同的对象,并输出相应成员的值。

using System;

using System.Collections.Generic;

using System.Text;

namespace exercise1

{

class Program

{

staticvoid Main(string[] args)

{

Console.Write("stu1:");

student stu1 = new student();

student stu2 = new student("张三");

Console.WriteLine("stu2:"+https://www.wendangku.net/doc/cf1953093.html,);

student stu3 = new student("20071234", "李四", true, 20);

Console.Write("stu3:{0},{1},{2},", stu3.id, https://www.wendangku.net/doc/cf1953093.html,, stu3.age);

stu3.printsex();

}

}

class student

{

publicstring id;

publicstring name;

publicint age;

publicbool sex;

publicvoid printsex()

{

if (sex == true)

Console.WriteLine("男");

else

Console.WriteLine("女");

}

public student(string i, string n, bool s, int a)

{

id = i; name = n; sex = s; age = a;

}

public student(string n)

{

name = n;

}

public student()

{

Console.WriteLine("没有初始化数据");

}

}

}

<14>

//(2)在控制台应用程序中创建Car类,在类中定义字段和属性。

//私有字段包括mcolor和mwheels,公有属性包括Color和Wheels。

//构造对象mycar,并设置属性颜色为“红色”,轮子数为4,最后输出属性的值。//要求:设计完成后,利用单步执行(快捷键F11),了解属性的调用过程。

using System;

using System.Collections.Generic;

using System.Text;

namespace exercise2

{

class Program

{

staticvoid Main(string[] args)

{

Car mycar = new Car();

mycar.Color = "红色";

mycar.Wheels = 4;

Console.WriteLine("颜色为:" + mycar.Color);

Console.WriteLine("轮子数为:" + mycar.Wheels);

}

}

class Car

{

privatestring mcolor;

privateint mwheels;

publicstring Color

{

get { return mcolor; }

set { mcolor = value; }

}

publicint Wheels

{

get { return mwheels; }

set { mwheels = value; }

}

}

}

<15>

//(3)定义一个描述复数的类Complex并测试。Complex类中包含两个私有字段,//用于保存复数的实部和虚部,相应属性用于访问字段。

//另外还定义有两个方法,分别用于对两个复数进行加、减四则运算,

//且有带参数的构造函数,用于在创建复数对象时初始化复数的实部和虚部。

using System;

using System.Collections.Generic;

using System.Text;

namespace exercise3

{

class Program

{

staticvoid Main(string[] args)

{

Complex c1 = new Complex(5, 6);

Complex c2 = new Complex(3, 4);

Console.WriteLine("复数1:{0}+{1}i", c1.Real, c1.Image);

Console.WriteLine("复数2:{0}+{1}i", c2.Real, c2.Image);

Complex a=c1.add(c2);

Console.WriteLine("其和为:{0}+{1}i", a.Real, a.Image);

Complex b = c1.sub(c2);

Console.WriteLine("其差为:{0}+{1}i", b.Real, b.Image);

}

}

class Complex

{

privateint real;

privateint image;

publicint Real

{

get { return real; }

set { real = value; }

}

publicint Image

{

get { return image; }

set { image = value; }

}

public Complex(int i, int j)

{

this.Real = i;

this.Image = j;

}

public Complex add(Complex x)

{

returnnew Complex(this.Real+x.Real ,this.Image +x.Image);

}

public Complex sub(Complex x)

{

returnnew Complex(this.Real- x.Real ,this.Image-x.Image);

}

}

}

<17>

//(4)创建一个描述图书信息的类并测试。

//类中应保存有图书的书号、标题、作者、出版社、价格等信息。

using System;

using System.Collections.Generic;

using System.Text;

namespace exercise4

{

class Program

{

staticvoid Main(string[] args)

{

Book b = new Book();

b.ISBN = "123456789";

b.Author = "张三";

b.Title = "无题";

b.Press = "出版社";

b.Price = 1.50;

Console.Write("{0},{1},{2},", b.ISBN, b.Author, b.Title); Console.WriteLine("{0},{1}", b.Press, b.Price);

}

}

class Book

{

privatestring isbn;

privatestring title;

privatestring author;

privatestring press;

privatedouble price;

publicstring ISBN

{

get { return isbn; }

set { isbn = value; }

}

publicstring Title

{

get { return title ; }

set { title = value; }

}

publicstring Author

{

get { return author ; }

set { author = value; }

}

publicstring Press

{

get { return press ; }

set { press = value; }

}

publicdouble Price

{

get { return price ; }

set { price = value; }

}

}

}

<18>

//(5)定义一个描述圆的类Circle。类中包含一个私有字段radius,

//用于保存圆的半径,一个属性Radius,用于读取和设置radius字段,

//并定义有一个默认构造函数和一个带参数的构造函数,用于初始化对象。

//另外,定义一个包含Main方法的类,在该类中定义一个方法CompareCircle,

//用于比较两个圆的大小,其中待比较的圆对象由参数传递,

//在Main方法中利用默认构造函数,创建一个半径为5的圆circle1,

//利用带参数的构造函数创建三个圆circle2、circle3、circle4(半径分别为8、10、5),//并调用方法CompareCircle比较circle1和其他三个圆的大小。

using System;

using System.Collections.Generic;

using System.Text;

namespace exercise5

{

class Program

{

staticvoid Main(string[] args)

{

Circle circle1 = new Circle();

circle1.Radius = 5;

Circle circle2 = new Circle(8);

Circle circle3 = new Circle(10);

Circle circle4 = new Circle(5);

CompareCircle(circle1, circle2);

CompareCircle(circle1, circle3);

CompareCircle(circle1, circle4);

}

publicstaticvoid CompareCircle(Circle a,Circle b)

{

if (a.Radius == b.Radius)

Console.WriteLine("半径为{0}圆与半径为{1}圆大小相同", a.Radius , b.Radius ); elseif (a.Radius > b.Radius)

Console.WriteLine("半径为{0}圆大于半径为{1}圆", a.Radius , b.Radius );

else

Console.WriteLine("半径为{0}圆小于半径为{1}圆", a.Radius , b.Radius );

}

}

class Circle

{

privatedouble radius;

publicdouble Radius

{

set { radius = value; }

get { return radius; }

}

public Circle()

{ }

public Circle(double r)

{

Radius = r;

}

}

}

<19>

//(7)编写一个矩形类,私有数据成员为矩形的长(len)和宽(wid),

//类包括取矩形的长度Len、取矩形的宽度Wid、

//求矩形的周长、求面积、修改矩形的长度和宽度为对应的形参值等公用属性和方法。//另外,无参构造函数将Len和Wid设置为0,有参构造函数设置Len和Wid的值。

//分别实例化不同的对象并调用相应成员。

using System;

using System.Collections.Generic;

using System.Text;

namespace exercise7

{

class Program

{

staticvoid Main(string[] args)

{

Rectangle r1 = new Rectangle();

r1.SetLen(3.5f); r1.SetWid(2.5f);

Console.WriteLine("r1周长为{0},面积为{1}", r1.Length(), r1.Area());

Rectangle r2 = new Rectangle(0.5f, 4.5f);

Console.WriteLine("r2周长为{0},面积为{1}", r2.Length(), r2.Area());

}

}

class Rectangle

{

privatefloat len;

privatefloat wid;

publicfloat Len

{

get { return len; }

set { len = value; }

}

publicfloat Wid

{

get { return wid; }

set { wid = value; }

}

publicfloat Length()

{

return (Len + Wid) * 2;

}

publicfloat Area()

{

return Len * Wid;

}

publicvoid SetLen(float l)

{ Len = l; }

publicvoid SetWid(float w)

{ Wid = w; }

public Rectangle()

{

Wid = 0; Len = 0;

}

public Rectangle(float l, float w)

{

Len = l; Wid = w;

}

}

}

<20>

//2、定义多边形类Polygon,在类中定义字段、属性和虚方法;

//由基类Polygon创建派生类Square和Pentagon。在派生类中实现方法重写;

//在程序中实例化类的对象并且调用类的方法实现多态性。

//要求:

//()基类Polygon包含以下成员:

//?私有字段length,代表边长,int型

//?私有字段sides,代表边数,int型

//?公有属性Length,用于获取和设置length字段。在构造函数中初始化为。

//?公有属性Sides,用于获取和设置sides字段。

//?虚方法GetPeri(),用于计算图形周长,方法返回类型为string。

//()定义派生类Square和Pentagon,在其中重写基类的虚方法。

//?在类Square的构造函数中,设置Sides为。

//?在类Pentagon的构造函数中,设置Sides为。

//?在派生类中,分别重写虚方法GetPeri(),方法返回一个字符串“The perimeter of the Polygon is x”,//其中x表示Length和Sides的乘积。

//()实例化类的对象,调用方法输出周长。

//?实例化Square的一个对象,设置Length值为,调用方法GetPeri()。

//?实例化Pentagon的一个对象,设置Length值为,调用方法GetPeri(),输出返回的字符串。

using System;

using System.Collections.Generic;

using System.Text;

namespace exercise1

{

class Program

{

staticvoid Main(string[] args)

{

Square s = new Square(); //?实例化Square的一个对象

s.Length = 2; //设置Length值为,

Console.WriteLine(s.GetPeri()); //调用方法GetPeri()。

Pentagon p = new Pentagon(); //?实例化Pentagon的一个对象

s.Length = 5; //设置Length值为

Console.WriteLine(s.GetPeri()); //调用方法GetPeri(),输出返回的字符串。

}

}

class Polygon

{

privateint length; //?私有字段length,代表边长,int型

privateint sides; //?私有字段sides,代表边数,int型

publicint Length //?公有属性Length,用于获取和设置length字段。

{

get { return length; }

set { length = value; }

}

public Polygon() //在构造函数中初始化(Length)为。

{

Length = 1;

}

publicint Sides //?公有属性Sides,用于获取和设置sides字段。

{

get { return sides; }

set { sides = value; }

}

publicvirtualstring GetPeri() //?虚方法GetPeri(),用于计算图形周长,方法返回类型为string。 {

return"this is a virtual mothod";

}

}

class Square : Polygon

{

public Square() //?在类Square的构造函数中,设置Sides为。

{

Sides = 4;

}

publicoverridestring GetPeri() //?在派生类中,重写虚方法GetPeri(),方法返回一个字符串“The perimeter of the Polygon is x”,其中x表示Length和Sides的乘积。

{

int x = Length * Sides;

return"The perimeter of the Polygon is " + x;

}

}

class Pentagon : Polygon

{

public Pentagon() //?在类Pentagon的构造函数中,设置Sides为。

{

Sides = 5;

}

publicoverridestring GetPeri() //?在派生类中,重写虚方法GetPeri(),方法返回一个字符串“The perimeter of the Polygon is x”,其中x表示Length和Sides的乘积。

{

int x = Length * Sides;

return"The perimeter of the Polygon is " + x;

}

}

}

<21>

假设你是一家银行的工作人员。要求你为帐户的类型定义对象。这些帐户是活期帐户(CheckingAccount)和储蓄存款帐户(SavingsAccount)。活期帐户具有以下特征:帐户持有者的名字只能在创建帐户时指定;初始金额必须在帐户创建时指定;帐户创建时必须分配帐户号。活期帐户的帐户号范围是从1000到4999,每个帐户必须具有唯一的帐户号。(不必检查帐户号的正确性)。活期帐户持有者能够:往帐户中加钱;如果帐户里资金充足,可以从中取钱。

储蓄存款帐户具有以下特征:帐户持有者的名字只能在创建帐户时指定;初始金额必须在帐户创建时指定;帐户创建时必须分配帐户号。储蓄存款帐户的帐户号范围是从5000到9999,每个帐户必须具有唯一的帐户号。(不必检查帐户号的正确性)。储蓄存款帐户持有者能够:往帐户中加钱;如果帐户里资金充足,可以从中取钱;帐户可以赚取利息,利率取决于帐户余额。如果余额大于1000,利息率是6%,否则是3%。

提示:可先定义基类BankAccout,然后定义派生类CheckingAccount和SavingsAccount。基类中包含派生类的共有成员。

using System;

using System.Collections.Generic;

using System.Text;

namespace exercise2

{

class Program

{

staticvoid Main(string[] args)

{

CheckingAccount ca = new CheckingAccount("张三", 1000);

Console.WriteLine("*******活期帐户*******");

Console.WriteLine("用户名:{0}\n帐号:{1}\n帐户初始金额:{2}", ca.CustomerName, ca.CustomerId, ca.CustomerBalance);

ca.Deposit(500);

Console.WriteLine("存入后的余额是:" + ca.CustomerBalance);

ca.Withdraw(800);

Console.WriteLine("取出后的余额是:{0}\n", ca.CustomerBalance);

SavingsAccount sa = new SavingsAccount("李四", 1500);

Console.WriteLine("*****储蓄存款帐户*****");

Console.WriteLine("用户名:{0}\n帐号:{1}\n帐户初始金额:{2}", sa.CustomerName, sa.CustomerId, sa.CustomerBalance);

sa.Deposit(300);

Console.WriteLine("存入后的余额是:{0}\n利率是:{1}", sa.CustomerBalance, sa.Rate);

sa.Withdraw(1000);

Console.WriteLine("取出后的余额是:{0}\n利率是:{1}", sa.CustomerBalance, sa.Rate);

}

}

class BankAccount

{

protectedint cid;

protectedstring cname;

protecteddecimal cbalance;

publicstring CustomerName

{

get { return cname; }

}

publicint CustomerId

{

get { return cid; }

}

publicdecimal CustomerBalance

{

get { return cbalance; }

}

publicvoid BankAccout(string n, decimal b)

{

cname = n;

cbalance = b;

}

publicvirtualvoid Deposit(decimal money)

{

cbalance += money;

}

publicvirtualbool Withdraw(decimal money)

{

if (money <= cbalance)

cbalance -= money;

returntrue;

}

else

returnfalse;

}

}

class CheckingAccount : BankAccount

{

staticprivateint seedId = 1000;

public CheckingAccount(string name, decimal balance) {

base.BankAccout(name, balance);

cid = seedId++;

}

}

class SavingsAccount : BankAccount

{

staticprivateint seedId = 5000;

public SavingsAccount(string name, decimal balance) {

base.BankAccout(name, balance);

cid = seedId++;

}

privatedecimal rate;

publicdecimal Rate

{

get

{

if (cbalance > 1000)

rate = 0.06M;

else rate = 0.03M;

return rate;

}

}

publicoverridevoid Deposit(decimal money)

{

base.Deposit(money);

rate = this.Rate;

}

publicoverridebool Withdraw(decimal money)

{

if (base.Withdraw(money))

相关文档