AI智能
改变未来

C# 设计控制台应用程序 对式子ax^2+bx+c=d求解

[code]using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ProgramDesign {class Program {static void Main(string[] args) {//Console.WriteLine(Answer2String(GetAnswer(1, 2, 1, 1)));//Console.WriteLine(Answer2String(GetAnswer(1, 1, 1, 1)));//Console.WriteLine(Answer2String(GetAnswer(1, 3, 1, 1)));Console.WriteLine(\"请输入a,b,c,d 四个整数,注意以英文逗号隔开\");string str = Console.ReadLine();string[] strs = str.Split(\',\');Console.WriteLine(Answer2String(GetAnswer(int.Parse(strs[0]), int.Parse(strs[1]), int.Parse(strs[2]), int.Parse(strs[3]))));Console.ReadKey();}/// <summary>/// 格式化方程的根为字符串/// </summary>public static string Answer2String(double[] answers) {if(double.IsNaN(answers[0])) {return \"方程无解\";}if(answers.Length == 1) {return $\"方程仅有一根:x = {answers[0]}\";}return $\"方程有两根:x1 = {answers[0]}, x2 = {answers[1]}\";}/// <summary>/// 获得一元二次方程的根/// </summary>public static double[] GetAnswer(double a, double b, double c, double d) {//判断是否有解double delta = Math.Pow(b, 2) - 4 * a * c;//是否有根if (delta < 0) {return new double[] { double.NaN };}if (delta == 0) {return new double[] { -b / 2 * a };}double deltaPow = Math.Sqrt(delta);return new double[] { (-b + deltaPow) / 2 * a, (-b - deltaPow) / 2 * a };}}}

运行结果:

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » C# 设计控制台应用程序 对式子ax^2+bx+c=d求解