C程序设计及应用课后题答案

  • 格式:docx
  • 大小:463.55 KB
  • 文档页数:21

下载文档原格式

  / 21
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

4、分别写出下列语句执行的结果。

1) Console.WriteLine("{0}--{0:p}good",12.34F);

2) Console.WriteLine("{0}--{0:####}good",0);

3) Console.WriteLine("{0}--{0:00000}good",456);

【解答】

12.34--1,234.00%good

0--good

456--00456good

5、编写一个控制台应用程序,输出1到5的平方值,要求:

1) 用for语句实现。

2) 用while语句实现。

3) 用do-while语句实现。

【解答】

using System;

using System.Collections.Generic;

using System.Text;

namespace outputSquareValue

{

class Program

{

static void Main()

{

//用for语句实现

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

{

Console.WriteLine("{0}的平方值为{1}", i, i * i);

}

//用while语句实现

int j = 0;

while (j++ < 5)

{

Console.WriteLine("{0}的平方值为{1}", j, j * j);

}

//用do-while语句实现

int k = 1;

do

{

Console.WriteLine("{0}的平方值为{1}", k, k * k);

} while (k++ < 5);

Console.ReadLine();

}

}

}

6、编写一个控制台应用程序,要求用户输入5个大写字母,如果用户输入的信息不满足要求,提示帮助信息并要求重新输入。

using System;

using System.Collections.Generic;

using System.Text;

namespace inputCapitalLetter

{

class Program

{

static void Main()

{

bool ok = false;

while (ok == false)

{

Console.Write("请输入5个大写字母:");

string str = Console.ReadLine();

if (str.Length != 5)

{

Console.WriteLine("你输入的字符个数不是5个,请重新输入。");

}

else

{

ok = true;

for (int i = 0; i < 5; i++)

{

char c = str[i];

if (c < 'A' || c > 'Z')

{

Console.WriteLine("第{0}个字符“{1}”不是大写字母,请重新输入。", i + 1, c);

ok = false;

break;

}

}

}

}

}

}

}

7、编写一个控制台应用程序,要求完成下列功能。

1) 接收一个整数n。

2) 如果接收的值n为正数,输出1到n间的全部整数。

3) 如果接收的值为负值,用break或者return退出程序。

4) 转到(1)继续接收下一个整数。

【解答】

using System;

using System.Collections.Generic;

using System.Text;

{

class Program

{

static void Main()

{

while (true)

{

Console.Write("请输入一个整数(负值结束):");

string str = Console.ReadLine();

try

{

int i = Int32.Parse(str);

if (i < 0) break;

for (int j = 1; j <= i; j++) Console.WriteLine(j);

}

catch

{

Console.WriteLine("你输入的不是数字或超出整数的表示范围,请重新输入");

}

}

}

}

}

8、编写一个控制台应用程序,求1000之内的所有“完数”。所谓“完数”是指一个数恰好

等于它的所有因子之和。例如,6是完数,因为6=1+2+3。

【解答】

using System;

using System.Collections.Generic;

using System.Text;

namespace completeNumber

{

class Program

{

static void Main(string[] args)

{

for (int i = 2; i <= 1000; i++)

{

int s = 1;

string str = "1";

for (int j = 2; j <= (int)Math.Sqrt(i); j++)

{

if (j * (i / j) == i)

{

if (j != i / j)

{