标签:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 函数_解一元二次方程_ { class Program { public static int jiefangcheng(int a, int b, int c,out double x1,out double x2) { int jieguo = 0; x1 = 0; x2 = 0; if (a == 0) { jieguo = -1; } else { int dert = b * b - 4 * a * c; if (dert < 0) { jieguo = 0; } else { if (dert > 0) { jieguo =2; x1 = (-b + Math.Sqrt(dert)) / (2 * a); x2 = (-b - Math.Sqrt(dert)) / (2 * a); } else { jieguo = 1; x1 = x2 = -b / (2 * a); } } } return jieguo; } static void Main(string[] args) { while (true) { Console.WriteLine("请输入a的值:"); int a = int.Parse(Console.ReadLine()); Console.WriteLine("请输入b的值:"); int b = int.Parse(Console.ReadLine()); Console.WriteLine("请输入c的值:"); int c = int.Parse(Console.ReadLine()); double x1, x2; int jieguo = jiefangcheng(a, b, c, out x1, out x2); if (jieguo == -1) { Console.WriteLine("不是一元二次方程"); } else if (jieguo == 0) { Console.WriteLine("无实根"); } else if (jieguo == 1) { Console.WriteLine("有两个相等的实根分别为x1={0},x2={1}", x1, x2); } else { Console.WriteLine("有两个不相等的实根分别为x1={0},x2={1}", x1, x2); } } Console.ReadLine(); } } }
switch来代替if 结构
switch (jieguo) { case -1: Console.WriteLine("不是一元二次方程"); break; case 0: Console.WriteLine("无实根"); break; case 1: Console.WriteLine("有两个相等的实根,分别为x1=x2={0}",x1); break; case 2: Console.WriteLine("有两个不相等的实根,分别为x1={0},x2={1}",x1,x2); break;
}
标签:
原文地址:http://www.cnblogs.com/kangshuai/p/4580978.html