c#认证习题
1.1奇偶数的求和
result += n; for (i = 0; i < n; i++) { n = n -2; result += n; }
1.2约数
//奇数的求约数方法
//偶数的求和方法与奇数类似
if (n % 2 != 0) { for (i = 3; i <= (n - 1) / 2; i++) if (n % i == 0) Console.WriteLine(i); }
1.3最大公约数
if (a > b) temp = b; else temp = a; Console.WriteLine("最大公约数为:"); for (i = temp; i >= 1; i--)//因为求最大,所以是递减 if (a % i == 0 && b % i == 0) { result = i; Console.WriteLine(result); break;//break所起的作用就是让for只执行一次,找出最大的就跳出循环 }
1.4最小公倍数
if (a > b) temp = b; else temp = a; for ( i = temp;i<=a*b;i++) { if (i % a == 0 && i % b == 0) { result = i; Console.WriteLine("最小公倍数为:{0}",result); break; } } Console.WriteLine("按回车键结束"); Console.ReadKey();
1.5素数的判断
for (i = 2; i <= n / 2; i++) { if (n % i == 0) { prime = false; break; } else prime = true; } { if (prime == true) { Console.WriteLine("{0}是素数", n); } else { Console.WriteLine("{0}不是素数", n); } }
1.6判断是否为平方数
for (i = 2; i <= n / 2; i++) { if (i * i == n) { square = true; break; } else square = false; } if (square == true) Console.WriteLine("该数为平方数,平方根为{0}", i); else Console.WriteLine("该数为非平方数");
1.7身份证格式和性别判断(15位)
if (s_ident.Length != 15)//不等于(!=) { Console.WriteLine("号码格式不正确"); return;//结束进程用return,跳出循环用break } for (i = 0; i < s_ident.Length; i++) { ch = s_ident[i]; if (ch < '0' || ch > '9') { Console.WriteLine("号码格式不正确"); return; } } { if (int.Parse(s_ident[s_ident.Length - 1].ToString()) % 2 == 0) Console.WriteLine("性别为女"); else Console.WriteLine("性别为男"); }
1.8 身份证格式和性别判断(18位)与15方法类似,只是if里面嵌套for循环
1.10求最小的ASCII码(9题相似)
ch = s_text[0]; for (i = 0; i < s_text.Length; i++) { if (s_text[i]< ch) ch = s_text[i]; }
1.11对字符串进行加密(ch与s_key的每个字符尽兴亦或运算(亦或运算的符号为^))
解密与加密的过程一样
for (i = 0; i < s_text.Length; i++) { ch = s_text[i]; //ch与s_key的每个字符尽兴亦或运算(亦或运算的符号为^) s_result += Convert.ToChar(ch ^ s_key[i]); }
1.13计算多个数的平均值(求平方和相似)
s_input = Console.ReadLine();//输入值
while (!(Convert.ToChar(s_input) == 'x' || Convert.ToChar(s_input) == 'X')) { total += int.Parse(s_input); count++; s_input = Console.ReadLine();//读取输入的值,重要作用 } total = total / count;
1.15十进制转为二进制(变为八进制时直接将2变为8,把while的条件改了)
while (number != 0) { //因为要将number添加到s_temp的末尾,所以要先s_temp赋值,再numer除2 s_temp = s_temp + (number % 2).ToString(); number = number / 2; } // s_temp = s_temp + number; for (i= s_temp.Length - 1;i > 0; i--) { s_binary += Convert.ToChar(s_temp[i]);
}
1.17计算笼子数量(分割的区间数,分别为1,2,5)
//选择笼子的前提必须是能把选择的这个笼子装满 while (amount > 0) { if (amount >= 5) amount = amount - 5; else if (amount >= 2 && amount < 5) amount -= 2; else amount -= 1; count++; }
1.18等级评估
level = credit / 10; switch (level) { case 9:Console.WriteLine("优秀");break; case 8:Console.WriteLine("良好");break; case 7:Console.WriteLine("一般");break; case 6:Console.WriteLine("及格");break; case 5: case 4: case 3: case 2: case 1: case 0: Console.WriteLine("不及格");break; default:Console.WriteLine("出错了");break; }
1.19计算打折情况
amount = int.Parse(Console.ReadLine());//根据题上所知单价为25 cost = amount * level;//单价为level,数量为amount level = Convert.ToInt32(Math.Log10(amount));//这里用int.parse不行 switch (level) { case 1:cost =int.Parse((cost*0.9).ToString());break; case 2:cost = int.Parse((cost * 0.85).ToString());break; case 3: cost = int.Parse((cost * 0.8).ToString()); break; }
1.20判断电话号码的类型
//这里不需要用for循环
if ((s_phone[0] != '1' && s_phone[1] != '3') || s_phone.Length!=11) { Console.WriteLine("无效的手机号码"); Console.ReadLine(); return; } else { switch(s_phone[2]) { case '0': case '1':Console.WriteLine("联通GSM用户");break; case '3':Console.WriteLine("联通CDMA用户");break; case '2': case '4':Console.WriteLine("无效的手机号码");break; case '5': case '6': case '7': case '8': case '9':Console.WriteLine("移动用户");break; default:Console.WriteLine("输入错误");break; } }
2.1派生动物类
public class Animal { private bool m_sex; int m_age; //用于get和set的公有属性(public +类型+属性名{get{return 所需属性}; set{所需属性=value};}) public bool Sex { get { return m_sex; } set { m_sex = value; } } //基类的构造函数(public+基类名{公有属性=}) public Animal() { Sex = false; } public int Age { get { return m_age; } set { m_age = value; } } //虚拟方法(public +virtual+方法返回值的类型+方法名) public virtual string Introduce() { if (Sex) return ("This is a male Animal!"); else return ("This is a female Animal!"); } } //在基类外面建立派生(public class(因为还是类)+类名+“:”+基类名) public class Dog : Animal { public Dog() { Sex = true; } //重写方法时要加一个override在方法类型后面 public override string Introduce() { if (Sex) return ("This is a male Dog!"); else return ("This is a female Dog!"); } } static void Main(string[] args) { //实例化对象就用new Dog dog = new Dog(); Console.WriteLine(dog.Introduce()); Console.WriteLine("按回车键结束"); Console.ReadKey(); }
2.2派生学生类与学生类相似只是给某个属性赋值时不一样
Undergraduate un = new Undergraduate(); un.Grade = 4; Console.WriteLine(un.Introduce());
2.3-2.10跟第一题相似
2.11定义动物类
//当定义一个抽象方法的时候要在基类class前面加abstract修饰 public abstract class Animal public abstract string Roal();//虚拟方法用abstract修饰 public class Dog :Animal { public Dog() { Sex = true; Sound = "Wow..."; } public override string Roal()//派生中重写方法时还是用override { return ("Dog:" + Sound); } } Animal animal;//构造类的变量直接类名+变量名 animal = new Dog(); Console.WriteLine(animal.Roal());
5.1字体转换的模式于非模式
private void button1_Click(object sender, EventArgs e) { FontDialog dlg = new FontDialog(); dlg.Font = label1.Font;//当前选择字体为label1的字体 //当字体对话框中按下“确定”,label1的字体变为所选的字体 if(dlg.ShowDialog()==DialogResult.OK) { label1.Font = dlg.Font; } } private void button1_Click(object sender, EventArgs e) { Form2 f = new Form2(); f.TopMost = true;//该窗体被置于最上层且无法改变 f.ShowDialog();//模式对话框 //f.Show为非模式对话框,非模式对话框时没有f.TopMost }
5.2button大小和label随之改变
private void button1_Click(object sender, EventArgs e) { FontDialog dlg = new FontDialog(); this.Show(); dlg.Font = this.Font;//把当前字体付给dlg的默认 //当字体对话框中按下“确定”,label1的字体变为所选的字体 if(dlg.ShowDialog()==DialogResult.OK) { this.Font = dlg.Font;//把dlg选中的字体付给当前(随字体大小Button大小随之改变) label1.Font = this.Font; } }
5.3前景色的改变
private void button1_Click(object sender, EventArgs e) { ColorDialog dlg = new ColorDialog(); dlg.Color =this.ForeColor;//ForeColor为前景色 if(dlg.ShowDialog()==DialogResult.OK) { this.ForeColor = dlg.Color; } }
5.4背景色的变化(跟前景色相似,属性改为BackColor)
5.5 label1的前景色的改变
this.label1.ForeColor = dlg.Color;
5.6 label1的背景色的改变
this.label1.BackColor = dlg.Color;
5.7利用Windows里面的对话框fontDialog控制字体下划线、删除线和字符集的控制表现在fontDialog的ShoweEffects和AllowScript上
5.8改变Form2的字体
this.Font = fontDialog1.Font;(form2用this代替)
5.9有应用按钮
fontDialog的ShowApply为true
5.10与9题相似,只是将label1改为this
后面的11-20题都相似
6.1绘图(绘制时用Draw,填充时用Fill)
private void Form1_Paint(object sender, PaintEventArgs e) { //定义直线的时候就用DrawLine e.Graphics.DrawString("这是一组同心圆环", this.Font, Brushes.Black, 10, 20);//处理代码 e.Graphics.FillEllipse(Brushes.Green, 40, 40, 160, 160); e.Graphics.FillEllipse(Brushes.Blue, 60, 60, 120, 120); e.Graphics.FillEllipse(Brushes.Yellow, 80, 80, 80, 80); e.Graphics.FillEllipse(Brushes.Red, 100, 100, 40, 40);//填充椭圆就用FillEllipse,x和y与宽和高都是矩形的
//e.Graphics.DrawArc(Pens.Green, 100, 100, 40, 40, 0, 360);//定义通过弧线画椭圆(圆)的时候,里面的x,y是包含椭圆的矩形的左上角的坐标,宽和高是矩形的宽和高,0和360的意思就是画圆 //e.Graphics.DrawPolygon(Pens.Green, new Point[] { new Point(220, 100), new Point(190, 120), new Point(200, 150), new Point(240, 150), new Point(250, 120) });//定义多边形的时候用DrawPolygon,Point要重新new一个 // e.Graphics.DrawArc(Pens.Red, new Rectangle(40, 40, 160, 160), 20, 100);//画弧线的时候,最后一个100是根据第一个角度减去第二个角度,20就是第一个角度 // e.Graphics.DrawPie(Pens.Blue, new RectangleF(40, 40, 160, 160), 260, 100);//画扇形的方法,填充就用fill //e.Graphics.DrawCurve(Pens.Blue, new Point[] { new Point(20, 100), new Point(80, 60), new Point(200, 140), new Point(260, 100) });//画曲线 // e.Graphics.DrawClosedCurve(Pens.Blue, new Point[] { new Point(20, 100), new Point(80, 60),new Point(140,100), new Point(200, 140), new Point(260, 100)});//画封闭的曲线不用重复第一个点 //e.Graphics.DrawEllipse(Pens.Purple, 40, 60,40, 120);//绘制椭圆 }
7.1文件保存与读取(文件操作的头文件引用添加一个using System.IO;
public void SaveInfo(string Path) { StreamWriter sw = new StreamWriter(Path); sw.WriteLine(textBox1.Text); sw.WriteLine(textBox2.Text); sw.WriteLine(dateTimePicker1.Value.ToLongDateString()); sw.WriteLine(textBox3.Text); sw.WriteLine(comboBox1.SelectedIndex); sw.WriteLine(textBox4.Text); sw.Close();//用完之后一定要关闭 } //读取文件显示 public void LoadInfo(string path) { StreamReader sr = new StreamReader(path); textBox1.Text = sr.ReadLine(); textBox2.Text = sr.ReadLine(); // dateTimePicker1.Text = sr.ReadLine();获取相关的文本 dateTimePicker1.Value = DateTime.Parse(sr.ReadLine());//获取时间值 textBox3.Text = sr.ReadLine(); // comboBox1.Text = sr.ReadLine();获取相关的文本 comboBox1.SelectedIndex = Int32.Parse(sr.ReadLine());//获取当前所选项的值(combox有很多项) textBox4.Text = sr.ReadLine(); sr.Close(); } private void button1_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog();//打开文件对话框框 dlg.InitialDirectory = Application.StartupPath; dlg.Filter = "商品信息文件(*.s71)|*.s71";//规定文件类型 if(dlg.ShowDialog()==DialogResult.OK) { LoadInfo(dlg.FileName); } this.toolStripStatusLabel1.Text = File.GetLastWriteTime(dlg.FileName).ToString(); } private void button2_Click(object sender, EventArgs e) { SaveFileDialog dlg = new SaveFileDialog();//保存窗口 dlg.InitialDirectory = Application.StartupPath; dlg.Filter = "商品信息文件(*.s71)|*.s71"; if(dlg.ShowDialog()==DialogResult.OK) { SaveInfo(dlg.FileName); } }
7.2以二进制的方式创建文件与上相似
FileStream fs = new FileStream(Path,FileMode.Create);//FileMode指定文件的打开方式 BinaryWriter bw = new BinaryWriter(fs);//以二进制的形式写入流 dlg.InitialDirectory = Application.StartupPath;//初始路径为程序启动路径 dateTimePicker1.Value = DateTime.Parse(br.ReadString()); //二进制的时候read时用Readstring comboBox1.SelectedIndex = Int32.Parse(br.ReadString());
7.6使用checkedlistbox的时候
//从被选的checkedlist的值挨个读取,写入也一样,radiobutton还是checkde
for(int i=0;i<checkedListBox1.Items.Count;i++)
{
this.checkedListBox1.SetItemChecked(i, br.ReadBoolean());//读取
}
for (int i= 0;i< checkedListBox1.Items.Count;i++)
{
bw.Write(this.checkedListBox1.GetItemChecked(i));//写入
}
//listbox的操作
for (int i = 0; i < listBox1.Items.Count; i++)
{
bw.Write(this.listBox1.Items[i].ToString());//二进制的时候与一般一样
}
this.listBox1.Items.Clear();
while (br.PeekChar() != -1)//二进制的时候Peekchar(),不是二进制的时候Peek()
{
this.listBox1.Items.Add(br.ReadString());
}
7.19绘图功能点
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private ArrayList PL = new ArrayList(); private void menuItem2_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.InitialDirectory = Application.StartupPath; ofd.Filter= "图像数据文件(*.s719)|*.s719"; if (ofd.ShowDialog() == DialogResult.OK) { LoadInfo(ofd.FileName); this.statusBarPanel1.Text = File.GetLastWriteTime(ofd.FileName).ToString(); } } private void Form1_MouseDown(object sender, MouseEventArgs e) { Point pt = new Point(e.X, e.Y); PL.Add(pt); Invalidate(); } private void Form1_Paint(object sender, PaintEventArgs e) { for (int i = 0; i < PL.Count - 1; i++) e.Graphics.DrawLine(Pens.Black, (Point)PL[i], (Point)PL[i + 1]); } public void SaveInfo(string Path) { StreamWriter sw = new StreamWriter(Path); foreach (Point i in PL) { Point pt = new Point(i.X, i.Y); sw.WriteLine(pt); } sw.Close(); PL.Clear(); Invalidate(); } public void LoadInfo(string Path) { Invalidate(); Graphics aa=this.CreateGraphics(); StreamReader sr=new StreamReader(Path); Point dd=new Point(); while(sr.Peek()!=-1) { string bb=sr.ReadLine(); string[] p=bb.Split(','); p[0]=p[0].Substring(3); p[1]=(p[1].Substring(2).TrimEnd('}')); Point q=new Point(Int32.Parse(p[0]),Int32.Parse(p[1])); PL.Add(q); } for(int i=0;i<PL.Count-1;i++) { aa.DrawLine(Pens.Black,(Point)PL[i],(Point)PL[i+1]); } sr.Close(); } private void menuItem3_Click(object sender, EventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.InitialDirectory=Application.StartupPath; sfd.Filter="图像数据文件(*.s719)|*.s719"; if (sfd.ShowDialog() == DialogResult.OK) { SaveInfo(sfd.FileName); } } private void Form1_Load(object sender, EventArgs e) { }
7.20二进制方法绘图
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private ArrayList PL = new ArrayList(); private void Form1_MouseDown(object sender, MouseEventArgs e) { Point pt = new Point(e.X, e.Y); PL.Add(pt); Invalidate(); } private void Form1_Paint(object sender, PaintEventArgs e) { for (int i = 0; i < PL.Count - 1; i++) e.Graphics.DrawLine(Pens.Black, (Point)PL[i], (Point)PL[i + 1]); } public void SaveInfo(string Path) { //打开创建文件 FileStream fs = new FileStream(Path,FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); //写入文件的内容 int count = PL.Count; bw.Write(count); for (int i = 0; i < count; i++) { bw.Write(((Point)PL[i]).X); bw.Write(((Point)PL[i]).Y); } bw.Close(); fs.Close(); } public void LoadInfo(string Path) { FileStream fs = new FileStream(Path,FileMode.Open); BinaryReader br = new BinaryReader(fs); int count = br.ReadInt32(); //读取文件内容 for (int i = 0; i < count; i++) { PL.Add(new Point(br.ReadInt32(),br.ReadInt32())); } Invalidate(); br.Close(); fs.Close(); } private void menuItem2_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.InitialDirectory = Application.StartupPath; dlg.Filter = "图像数据文件(*.s719)|*.s719"; if (dlg.ShowDialog() == DialogResult.OK) { LoadInfo(dlg.FileName); this.statusBarPanel1.Text = File.GetLastWriteTime(dlg.FileName).ToString(); } } private void menuItem3_Click(object sender, EventArgs e) { SaveFileDialog dlg = new SaveFileDialog(); dlg.InitialDirectory = Application.StartupPath; dlg.Filter = "图像数据文件(*.s719)|*.s719"; if (dlg.ShowDialog() == DialogResult.OK) { SaveInfo(dlg.FileName); } } private void Form1_Load(object sender, EventArgs e) { } }