本次測試共三道題目,要求如下:<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
1. 請用C#完成
2. 開卷獨立完成,可以看書,上網等任何方式查找資料,但必須保證獨立完成。一旦發現有不誠實行爲,本公司將不予錄取,後果自負。
題目一:
1. 編寫冒泡排序程序
要求:
1) 請用C#編寫一個冒泡排序的程序,
2) 要求排序的數據從文件C:/DATA.DAT中讀取,數據間用逗號分隔。
解:
using System;
using System.IO;
class Test{
static void BubbleSort(int[] ai) {
for (int j = ai.Length - 1; j > 0; j--){ // outer loop (backward)
for (int i = 0; i < j; i++) // inner loop (forward)
if (ai[i] > ai[i+1]) Swap(ref ai[i], ref ai[i+1]);
}
}
static void Swap(ref int x,ref int y) {
x = x + y;
y = x - y;
x = x - y;
}
static void <?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" />Main(string[] args) {
int[] ai = getData();
BubbleSort(ai);
foreach (int i in ai) Console.WriteLine(i);
Console.ReadLine();
}
public static int[] getData(){
try{
StreamReader sr = new StreamReader("data.dat");
string sLine;
sLine = sr.ReadLine();
string[] astr = sLine.Split(new Char[]{','});
int[] ai = new int[astr.Length];
for(int i = 0; i < astr.Length; i++)
ai[i] = Convert.ToInt32(astr[i]);
return ai;
}
catch (Exception e) {
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
return null;
}
}
}
2.完成下面函數
public static string Left(string sSource, int iLength)
{
//完成類似於VB的Left函數的功能(返回字符串sSource的左iLength位的字符串)。
}
解:
using System;
class Test{
public static void Main(){
//完成類似於VB的Left函數的功能(返回字符串sSource的左iLength位的字符串)。
Console.WriteLine("Please enter a string to treaded:");
string s = Console.ReadLine();
int i = 0;
bool bInputValid = false;
while(!bInputValid){
try{
Console.WriteLine("Please enter the length from left most:");
i = Convert.ToInt32(Console.ReadLine());
if(i > s.Length) throw new Exception("");
}
catch(Exception e){
Console.WriteLine("It seen that your input data is not a integer or over flow, try again!");
Console.WriteLine(e.Message);
continue;
}
bInputValid = true;
}
Console.WriteLine("The left part string is {0} ", Left(s, i));
}
public static string Left(string sSource, int iLength){
char[] achar = new char[iLength];
for(int i = 0; i < iLength; i++)
achar[i] = sSource[i];//直接可字串中的單個字符,關鍵在這兒了
string sLeftPart = new string(achar);//直接構造回一個string
return sLeftPart;
}
}
2. 動物(animals)中的貓(cat)和狗(dog)都有咬(bit)的動作。請運用.net中對象的多態性技術展示貓咬和狗咬的動作。要求用C#代碼實現。
解:
using System;
public class animals{
//string sName;
public virtual void bit(){
Console.Write("i am animals");
}
}
public class dog : animals{
public override void bit(){
Console.Write("bit by a dag!");
}
}
public class cat : animals{
public override void bit(){
Console.Write("bit by a cat!");
}
}
public class Test{
public static void Main(){
animals[] aa = new animals[2];
aa[0] = new dog();
aa[1] = new cat();
foreach(animals a in aa) a.bit();
}
}