다음은 이차방정식 x^2 - x - 1 = 0 의 양의 근 즉 황금비율(golden ratio)을 구하는 C# 컨솔 애플리케이션 소스이다. 황금비율을 구하는 비례방정식은 1 : x = x : (x+1) 이며, 이를 이차방정식으로 표현한 것이 x^2 - x - 1 = 0 이다.
See: Golden ratio - Sajun.org
- /*
- * Filename: TestGoldenRatioApp.cs
- * 황금률(즉, 이차방정식 x^2 - x - 1 = 0 의 양의 근)을 계산한다.
- *
- * Compile: csc TestGoldenRatioApp.
- *
- * Execute: TestGoldenRatioApp
- *
- * Date: 2009/01/16
- * Author: PH Kim [ pkim (AT) scripts.pe.kr ]
- */
- using System;
- using System.Collections.Generic;
- namespace MyTestApplication1 {
- public class TestGoldenRatioApp {
- public static void PrintUsing() {
- Console.WriteLine("Using: TestGoldenRatioApp [-h|-help]");
- Console.WriteLine("This calculates the value of the golden ratio.");
- }
- // 이차방정식 a x^2 + b x + c = 0 의 근을 구한다.
- public List<double> FindQuadraticRoot(double a, double b, double c) {
- double x1, x2;
- if (a == 0.0) {
- throw new Exception("Since the highest coefficient is zero, the given equation is not a quadratic equation.");
- }
- else if (b*b - 4*a*c < 0.0) {
- throw new Exception("Since the discriminant " + (b*b - 4*a*c) + " is negative, the given equation has no real root.");
- }
- x1 = (-b + Math.Sqrt(b*b - 4*a*c)) / (2.0 * a);
- x2 = (-b - Math.Sqrt(b*b - 4*a*c)) / (2.0 * a);
- List<Double> array = new List<double>();
- array.Add(x1);
- array.Add(x2);
- return array;
- }
- // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
- public static void Main(string[] args) {
- TestGoldenRatioApp app = new TestGoldenRatioApp();
- if (args.Length > 0 && (args[0].Equals("-h") || args[0].Equals("-help"))) {
- PrintUsing();
- Environment.Exit(1);
- }
- try {
- List<double> values = app.FindQuadraticRoot(1.0, -1.0, -1.0);
- double x1, x2;
- x1 = values[0];
- x2 = values[1];
- if (x1 >= x2) {
- Console.WriteLine("The bigger root is " + x1 + ", ");
- Console.WriteLine("and the less root is " + x2 + ".");
- }
- else {
- Console.WriteLine("The bigger root is " + x2 + ", ");
- Console.WriteLine("and the less root is " + x1 + ".");
- }
- }
- catch (Exception caught) {
- Console.WriteLine("" + caught);
- }
- }
- }
- }
컴파일> csc TestGoldenRatioApp.cs
실행> TestGoldenRatioApp
The bigger root is 1.618033988749895,
and the less root is -0.6180339887498949.
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
'프로그래밍 > C#' 카테고리의 다른 글
진법(radix) 표 만들기 예제 with C# (0) | 2009.01.19 |
---|---|
대화형 모드의 진법(radix) 변환 예제 with C# (0) | 2009.01.16 |
현재 시각 알아내기 for C# (0) | 2009.01.16 |
조립제법(Horner의 방법) 예제 for C# (0) | 2009.01.16 |
80컬럼 컨솔에 19단표 출력하기 예제 for C# (0) | 2009.01.16 |