您的位置:首页 > 编程语言 > C#

C#入门经典(第4版)第五章习题

2010-08-31 20:26 232 查看
(1)下面的转换哪些不是隐式转换?

1.int转换为short

2.short转换为int

3.bool转换为string

4.byte转换为float

答案:

1和3不是隐式转换。

(2)基于short类型的color枚举包含彩虹的颜色,再加上黑色和白色,据此编写color枚举的代码。这个枚举可以使用byte类型吗?

答案:

enum color : short
{
Red, Orange, Yellow, Green, Blue, Indigo, Violet, Black, White
}

可以使用byte,因为byte可以存放0-255的值。

(3)修改第四章的mandelbrot图像生成实例,使用下面的结构表示复数:

struct imagNum

{

    public double real,imag;

}

答案:

这道题不会做,附参考答案。

static void Main(string[] args)
{
imagNum coord, temp;
double realTemp2, arg;
int iterations;
for (coord.imag = 1.2; coord.imag >= -1.2; coord.imag -= 0.05)
{
for (coord.real = -0.6; coord.real <= 1.77; coord.real += 0.03)
{
iterations = 0;
temp.real = coord.real;
temp.imag = coord.imag;
arg = (coord.real * coord.real) + (coord.imag * coord.imag);
while ((arg < 4) && (iterations < 40))
{
realTemp2 = (temp.real * temp.real) - (temp.imag * temp.imag)
- coord.real;
temp.imag = (2 * temp.real * temp.imag) - coord.imag;
temp.real = realTemp2;
arg = (temp.real * temp.real) + (temp.imag * temp.imag);
iterations += 1;
}
switch (iterations % 4)
{
case 0:
Console.Write(".");
break;
case 1:
Console.Write("o");
break;
case 2:
Console.Write("O");
break;
case 3:
Console.Write("@");
break;
}
}
Console.Write("/n");
}
}

(4)下面的代码可以成功编译吗?如果不能,为什么?

string[] blab = new string[5]

string[5] = 5th string.

答案:

不能成功编译。

因为sting数组最后一位是blab[4]。

5th string需要双引号。

没有分号。

(5)编写一个控制台应用程序,它接收用户输入的一个字符串,将其中的字符以与输入相反的顺序输出。

答案:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string myString; //定义字符串
Console.WriteLine("请输入一个字符串:");
myString=Console.ReadLine(); //给字符串取值
char[] words = myString.ToCharArray(); //获得一个可写的数组
Array.Reverse(words); //反转字符串顺序
string i = new string(words); //将word初始化为i的值
Console.WriteLine("结果为:");
Console.WriteLine("{0}", i); //输出i
Console.WriteLine("任意键结束!");
Console.ReadKey();

}
}
}

(6)编写一个控制台应用程序,它接收一个字符串,用yes替换字符串中所有的no。

答案:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{

string a; //定义字符串
Console.WriteLine("请输入一个字符串:");
a=Console.ReadLine(); //给字符串取值
a = a.Replace("no", "yes"); //对字符串进行替换
Console.WriteLine("结果为:");
Console.WriteLine(a); //输出字符串
Console.WriteLine("任意键结束!");
Console.ReadKey();
}
}
}

(7)编写一个控制台应用程序,给字符串中的每个单词加上双引号。

答案:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("输入一个字符串:");
string myString = Console.ReadLine();
myString = "/"" + myString.Replace(" ", "/" /"") + "/"";
Console.WriteLine("在每个单词上添加双引号: {0}", myString);
Console.ReadKey();
// myString.re

}
}
}

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