福建农林大学C#程序设计总复习材料 联系客服

发布时间 : 星期日 文章福建农林大学C#程序设计总复习材料更新完毕开始阅读382097a37c1cfad6185fa718

}

if (!flag) //如果没有发生交换,终止算法 return; } } }

9、请编程实现随机生成1000个0-99之间的整数,并完成每个整数出现的次数的统计。 【参考代码】 static void Main(string[] args) {

int[] numbers = new int[1000]; Random rand = new Random();

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

numbers[i] = rand.Next(100); }

int[] counts = new int[100]; foreach (int n in numbers) {

++counts[n]; }

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

Console.WriteLine(\数字{0}出现了{1}次\ }

Console.ReadKey(); }

10、下面代码实现将十进制的整数转换为对应的二进制数串。 【参考代码】

static string ConvertIntToBinary(int n) {

string binary = string.Empty; int i = n; int m = 0; while (i > 1) {

i = n / 2; m = n % 2;

binary = m.ToString() + binary; n = i; }

if (i > 0) binary = \ return binary;

}

11、请编写一个方法,求两个整数的之和,要求在方法体内不得使用+、-、×、÷。 【参考代码】

static int AddWithoutArithmetic(int num1, int num2) {

if (num2 == 0) return num1;

int sum = num1 ^ num2;

int carry = (num1 & num2) << 1;

return AddWithoutArithmetic(sum, carry);

}

12、假设某公司有几千名员工,请完成一个时间复杂度为O(n)的算法对该公司员工的年龄作排序,可使用O(1)的辅助空间。

【参考代码】该方法用长度为60的整数数组timesOfAge辅助空间,换来了O(n)的时间效率。不论对多少人的年龄进行排序,辅助数组的长度timesOfAge的大小固定,因此它的空间复杂度是个常数,即O(1)。 void SortAges(int []ages) {

const int oldestAge = 59;

int [] timesOfAge = new int[oldestAge + 1];

//数组timesOfAge统计每个年龄出现的次数

for(int i = 0; i <= oldestAge; i++) timesOfAge[i] = 0;

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

int age = ages[i]; ++timesOfAge[age]; }

int index = 0;

for(int i = 0; i <= oldestAge; ++ i) {

for(int j = 0; j < timesOfAge[i]; ++ j) {

ages[index] = i; ++ index; } }

}

13、多态性的应用。 例如:方法重载类

public class MathMtics

{

public int Max(int x, int y)//求两个整数的较大值 {if(x>y) return x; else return y; }

public char Max(char x,char y)//求两个字符的较大值 {

If(x>y) return x; else return y } };