C#网络应用编程基础练习题与答案[4]
时间:2007-04-20 来源:大学生计算机等级考试 打印本文
11. 编写一个控制台应用程序,要求完成下列功能。
1) 接收一个整数n。
2) 如果接收的值n为正数,输出1到n间的全部整数。
3) 如果接收的值为负值,用break或者return退出程序。
4) 转到(1)继续接收下一个整数。
【解答】
以下是引用片段:
using System;
using System.Collections.Generic;
using System.Text;
namespace testOutput
{
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("你输入的不是数字或超出整数的表示范围,请重新输入");
}
}
}
}
}
12. 编写一个控制台应用程序,求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)
{
s += j + i / j;
str += string.Format("+{0}+{1}", j, i / j);
}
else
{
s += j;
str += string.Format("+{0}", j);
}
}
}
if (s == i) Console.WriteLine("{0}={1}", i, str);
}
Console.ReadLine();
}
}
}

上一篇:计算机等级考试二级C++考点分析之类和对象
下一篇:C#网络应用编程基础练习题与答案[3]


