out 传值(传址)
传值,只将这个变量的值给拿走,不返还,除非return赋值。
将a的值传入函数,无论这个值在函数中如何变化,不会影响main中的a
传址,将这个变量的值拿走运算,完成后还是得返还回来(不用return,用out)
将a的值传入函数,函数中这个值如何变化,main中的a也会跟着变化
相当于:函数中的这个值,是main种这个a的快捷方式
求解一元二次方程的根,利用out传值返回x1和x2两个值
1 public void Fangcheng(double a, double b, double c, out double x1, out double x2) 2 { 3 double de = b * b - 4 * a * c; 4 if (de > 0) 5 { 6 Console.WriteLine("此方程有两个不相同的实数根!"); 7 x1 = (-b + Math.Sqrt(de)) / (a * 2); 8 x2 = (-b - Math.Sqrt(de)) / (a * 2); 9 } 10 else//de==0 11 { 12 Console.WriteLine("此方程有两个相同的实数根!"); 13 x1 = (-b + Math.Sqrt(de)) / (a * 2); 14 x2 = x1; 15 } 16 static void Main(string[] args) 17 { 18 double x1; 19 double x2; 20 Console.WriteLine("求解一元二次方程ax^2+bx+c=0的根的情况及结果:"); 21 Console.Write("请输入a="); 22 double a = double.Parse(Console.ReadLine()); 23 if (a == 0) 24 { 25 Console.WriteLine("此方程不是一元二次方程!"); 26 } 27 else 28 { 29 Console.Write("请输入b="); 30 double b = double.Parse(Console.ReadLine()); 31 Console.Write("请输入c="); 32 double c = double.Parse(Console.ReadLine()); 33 34 double de = b * b - 4 * a * c; 35 if (de < 0) 36 { 37 Console.WriteLine("此方程没有实数根!"); 38 } 39 else//de>=0 40 { 41 Program pp = new Program(); 42 pp.Fangcheng(a, b, c, out x1, out x2); 43 44 if (x1 == x2) 45 { 46 Console.WriteLine("x1=x2=" + x1); 47 } 48 else 49 { 50 Console.WriteLine("x1=" + x1); 51 Console.WriteLine("x2=" + x2); 52 } 53 } 54 } 55 56 Console.ReadLine();
}
猜拳游戏:与电脑进行猜拳游戏,输入剪刀,石头,布。
1 public void caiquan() 2 { 3 Console.Write("请出拳:"); 4 string x = Console.ReadLine(); 5 int x1; 6 if (x == "剪刀" || x == "石头" || x == "布") 7 { 8 switch (x) 9 { 10 case "剪刀": 11 x1 = 0; 12 break; 13 case "布": 14 x1 = 1; 15 break; 16 default: 17 x1 = 2; 18 break; 19 } 20 Random ran = new Random(); 21 int a = ran.Next(3); 22 string m; 23 switch (a) 24 { 25 case 0: 26 m = "剪刀"; 27 break; 28 case 1: 29 m = "布"; 30 break; 31 default: 32 m = "石头"; 33 break; 34 } 35 Console.WriteLine(m); 36 37 if ((x1 - a == -1) || (x1 - a == 2)) 38 { 39 Console.WriteLine("你赢了!"); 40 } 41 else if ((x1 - a == 1) || (x1 - a == -2)) 42 { 43 Console.WriteLine( "你输了"); 44 } 45 else 46 { 47 Console.WriteLine( "平局!"); 48 } 49 50 } 51 else 52 { 53 Console.WriteLine( "你的输入有误!"); 54 } 55 } 56 static void Main(string[] args) 57 { 58 Program p = new Program(); 59 p.caiquan(); 60 Console.ReadLine(); 61 }