예시 input
1 4 5
예시 output
-2 + i, -2 - i
C#
using System;
using System.Numerics;
namespace 허근까지
{
class Program
{
static void Main()
{
var solution = new QuadraticEquation(1, 4, 5);
Console.WriteLine(solution);
}
}
class QuadraticEquation
{
private readonly double quadraticCoeff, linearCoeff, constantCoeff;
public QuadraticEquation(double quadraticCoeff, double linearCoeff, double constantCoeff)
{
this.quadraticCoeff = quadraticCoeff; // 2차항 계수
this.linearCoeff = linearCoeff; // 1차항 계수
this.constantCoeff = constantCoeff; // 상수항 계수
this.Discriminant = Math.Pow(linearCoeff, 2.0) - 4.0 * this.quadraticCoeff * this.constantCoeff;
}
// 판별식
public double Discriminant { get; }
// 해를 문자열 표현으로 반환
public override string ToString()
{
Complex solution1 = (-linearCoeff + Complex.Sqrt(Discriminant)) / (2.0 * quadraticCoeff);
Complex solution2 = (-linearCoeff - Complex.Sqrt(Discriminant)) / (2.0 * quadraticCoeff);
string expression1 = Complex2Expression(solution1);
string expression2 = Complex2Expression(solution2);
return Discriminant == 0 ? $"{expression1}" : $"{expression1}, {expression2}";
}
// 복소수 클래스를 문자열 표현으로 변환
private static string Complex2Expression(Complex complex)
{
// 해의 정수 반올림
int realValue = (int)Math.Round(complex.Real);
int imagValue = (int)Math.Round(complex.Imaginary);
// 해를 경우따른 문자열로 표현
string first = realValue != 0 ? $"{realValue}" : "";
string sign = imagValue < 0 ? "-" : "+";
string second = Math.Abs(imagValue) != 1 ? $"{Math.Abs(imagValue)}i" : "i";
if (imagValue == 0)
{
second = string.Empty;
sign = string.Empty;
}
string expression = $"{first}{sign}{second}";
if (expression == "")
{
expression = "0";
}
return expression;
}
}
}
using System;
namespace solution
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("이차방정식 ax2 + bx + c = 0 에서 a b c 을 입력하세요.(예: 1 -3 2)");
string[] coeff = Console.ReadLine().Split(' ');
Console.WriteLine("{0}x2 + {1}x + {2} = 0 의 해: {3}",coeff[0], coeff[1], coeff[2], solution(coeff));
}
private static string solution(string[] coeff)
{
string ans = "";
double a = double.Parse(coeff[0]);
double b = double.Parse(coeff[1]);
double c = double.Parse(coeff[2]);
double D = b * b - 4 * a * c;
string strD = "";
if (D < 0)
{
int rootD = (int)Math.Round(Math.Sqrt(-D) / (2 * a));
strD = rootD == 1 ? "i" : rootD.ToString() + "i";
if (-b / (2 * a) == 0)
ans = strD + " , -" + strD;
else
ans = Math.Round(-b/(2*a)) + " + " + strD + " , " + Math.Round(-b / (2 * a)) + " - " + strD;
}
else if (D > 0)
{
double dd = Math.Sqrt(D) / (2 * a);
Console.WriteLine(-b / (2 * a) + " : "+ dd);
ans = Math.Round((-b - Math.Sqrt(D)) / (2 * a)).ToString() + " , " + Math.Round((-b + Math.Sqrt(D)) / (2 * a)).ToString();
}
else
ans = Math.Round(-b/(2*a)).ToString();
return ans;
}
}
}
2023年06月18日 19:48
풀이 작성
코딩도장은 프로그래밍 문제풀이를 통해서 코딩 실력을 수련(Practice)하는 곳입니다.