다음은  이차방정식 x^2 - x - 1  = 0 의 양의 근 즉 황금비율(golden ratio)을 구하는 C 애플리케이션 소스이다. 황금비율을 구하는 비례방정식은   1 : x = x : (x+1) 이며, 이를 이차방정식으로 표현한 것이 x^2 - x - 1  = 0 이다.

See:  Golden ratio - Sajun.org

아래의 소스파일은 C  언어용으로 민들어 두었던 소스 황금비율(golden ratio) 구하기 withfC and Ch 를 아주 조금 수정한 것이다. 수정한 부분은 #include를 #import로 바꾸고, 또

        #import  <Foundation/Foundation.h>

를 추가하고, 또 double 타입의 부동소수점수를 출력하기위한 printf 포맷에 %lf 대신 %g를 사용하역다. (만일 Foundation.h 를 수입(import)하지 않으면, exit 에러가 발생한다.)

컴파일은 Dev-C++ 개발 도구에서 Ctrl+F11 을 클릭한다.

  1. /*
  2.  *  Filename: testGoldenRatioMain.m
  3.  *    황금률(즉, 이차방정식 x^2 - x - 1  = 0 의 양의 근)을 계산한다.
  4.  *
  5.  *   Compile: Click Ctrl+F11
  6.  *
  7.  *   Execute: testGoldenRatio
  8.  *
  9.  *      Date:  2012/04/30
  10.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  11.  */
  12. #import <Foundation/Foundation.h>   // for exit()
  13. #import <stdio.h>
  14. #import <string.h>
  15. #import <math.h>
  16. typedef struct _PAIR {
  17.     double x1;
  18.     double x2;
  19. } PAIR;
  20. void printUsing() {
  21.     printf("Using: testGoldenRatio [-h|-help]\n");
  22.     printf("This calculates the value of the golden ratio.\n");
  23. }
  24. // 이차방정식 a x^2 + b x + c  = 0 의 근을 구한다.
  25. PAIR *findQuadraticRoot(double a, double b, double c) {
  26.     static PAIR zeros;
  27.     if (a == 0.0) {
  28.         fprintf(stderr, "Since the highest coefficient is zero, the given equation is not a quadratic equation.\n");
  29.         exit(1);
  30.     }
  31.     else if (b*b - 4*a*c < 0.0) {
  32.         fprintf(stderr, "Since the discriminant %f is negative, the given equation has no real root.\b", b*b - 4*a*c);
  33.     exit(1);
  34.     }
  35.     zeros.x1 = (-b + sqrt(b*b - 4*a*c)) / (2.0 * a);
  36.     zeros.x2 = (-b - sqrt(b*b - 4*a*c)) / (2.0 * a);
  37.     return (PAIR *)&zeros;
  38. }
  39. void main(int argc, const char *argv[]) {
  40.     PAIR *values;
  41.     double x1, x2;
  42.     if (argc > 1 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0)) {
  43.         printUsing();
  44.         exit(1);
  45.     }
  46.     values = findQuadraticRoot(1.0, -1.0, -1.0);
  47.     x1 = values->x1;
  48.     x2 = values->x2;
  49.     if (x1 >= x2) {
  50.        // neither %lg nor %lf, but %g or %f for Object-C
  51.         printf("The bigger root is %g, \n", x1);
  52.         printf("and the less root is %g.\n", x2);
  53.     }
  54.     else {
  55.        // neither %lg nor %lf, but %g or %f for Object-C
  56.         printf("The bigger root is %g, \n", x2);
  57.         printf("and the less root is %g.\n", x1);
  58.     }
  59. }



컴파일은 Dec-C++ 개발 도구에서 Ctrl+F11 클릭

실행> testGoldenRatio
The bigger root is 1.61803,
and the less root is -0.618034.



Posted by Scripter
,