c#输入一个数字n,判断是否为正整数,是正整数逐个输出0~n和n的阶乘,不是正整数输出你输入的不是数字或者超过正整数的范围。
1.采用for循环
Program.cs
[sourcecode language=”c”]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.Write("请输入一个整数:");
string str = Console.ReadLine();
bool isNumber = System.Text.RegularExpressions.Regex.IsMatch(str, @"^[1-9]\d*$");
if (isNumber)
{
int b;
int s=0;
b = int.Parse(str);
for (int i = 0; i <= b; i++)
{
Console.WriteLine(i);
s=i+s;
}
Console.WriteLine(s);
}
else
{
Console.Write("你输入的不是数字或者超过正整数的范围");
}
Console.ReadKey();
}
}
}
}
[/sourcecode]
2.采用do-while循环
Class1.cs
[sourcecode language=”c”]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
while (true)
{
Console.Write("请输入一个整数:");
string str = Console.ReadLine();
bool isNumber = System.Text.RegularExpressions.Regex.IsMatch(str, @"^[1-9]\d*$");
if (isNumber)
{
int b;
int s = 0;
b = int.Parse(str);
int i=0;
do
{
i++;
Console.Write(i);
Console.Write(" ");
s = i + s;
}while(i < b);
Console.WriteLine("");
Console.WriteLine("{0}的阶层={1}", b, s);
}
else
{
Console.Write("你输入的不是数字或者超过正整数的范围");
}
Console.ReadKey();
}
}
}
}[/sourcecode]
效果图: