C# 长浏览
1)C# 求阶乘
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
递归方法:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(fun(6).ToString());
Console.ReadKey();
}
public static double fun(int n)
{
if (n == 1)
return 1;
else
return fun(n - 1) * n;
}
}
}
非递归方法:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(fun(6).ToString());
Console.ReadKey();
}
public static double fun(int n)
{
double S = 1;
for (int i = 0; i < n; i++)
{
S *= (i+1);
}
return S;
}
}
}
2)C#题目,用递归算法算1.1.2.3.5.8.13....第30个是多少 ( 斐波那契)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static int Add(int i)
{
if (i <= 0)
{
return 0;
}
else if (i > 0 && i <= 2)
{
return 1;
}
else
{
return Add(i - 1) + Add(i - 2);
}
}
3) C# 基础
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
C#基础
ArrayList
ArrayList al;
al =new ArrayList();
string s = Console.ReadLine();
while(s !="q")
{ al.Add(s);
s = Console.ReadLine();
}
for(int i=0;i<al.Count;i++)
Console.WriteLine(al[i].ToString());
从键盘输入一个数组,并求最大
int[] a;
Console.WriteLine("Pls input len:");
int len = Convert.ToInt32(Console.ReadLine());
a = new int[len];
Console.WriteLine("Pls input array");
for(int i=0;i<len;i++)
{ a[i]=Convert.ToInt32(Console.ReadLine()); }
for(int j=0;j<a.Length;j++)
Console.WriteLine(a[j]);
for(int k=0;k<a.Length;k++)
{ if(a[0]<a[k])
a[0]=a[k];
} Console.WriteLine(a[0]);
递归
int fac (int n)
{ if(n==0) return 1;
return n*fac(n-1);
}
斐波那契数列第n项
int fib (int n)
{ if(n==1) return 1;
if(n==2) return 1;
return fib(n-1)+fib(n-2);
}
递归求1加到100
public int Fac(int n)
{ if(n==1) return 1;
return
……………………………………
;
}
static void Main()
{ math f=new math();
int s=f.Fac(100);
Console.WriteLine(s);
}
求前24项斐波那契序列数
static int fib(int n)
{ if(n==1) return 1;
if(n==2) return 1;
return fib(n-1)+fib(n-2);
}
static void Main(string[] args)
{ int t=0;
for(int i=1;i<25;i++)
{ t=fib(i);
Console.WriteLine(t);
} }
汉诺塔
static void Hanoi(string X, string Y,string Z,int n)
{ if(n==1)
{ Console.WriteLine(X + "-->" +Z);
return;
}
Hanoi (X,Z,Y,n-1);
Console.WriteLine(X+"-->"+Z);
Hanoi (Y,X,Z,n-1);
}
static void Main(string[] args)
{ Hanoi("A","B","C",5); }
3位的水仙花数
for(int i=100;i<1000;i++)
{ int a=i/100; int c=i%10; int b=((i-c)/10)%10;
if(i==a*a*a+b*b*b+c*c*c)
Console.WriteLine(i);
}
StringBuilder
class A
{ static void Main()
{ StringBuilder a=new StringBuilder();
a.Append ("asa");
a.Append ("www");
string s=a.ToString();
Console.WriteLine(s);
}
} 结果:asawww
singleton设计模式
class A
{ private int v;
A(int x)
{ v=x; }
public int V
{ get{return v;} }
static A c=null;
public static A fun(int n)
{ if(c==null)
c=new A(n);
return c;
}
}
class B
{ static void Main(string[] args)
{ A c=A.fun(2);
Console.WriteLine(c.V);
c=A.fun(8);
Console.WriteLine(c.V);
}
} 结果:2,2