D 언어의 if ... else ... 조건문 구문은 C/C++/Java/Groovy 의 것과 같다.
단, 한글이 포함된 소스파일은 UTF-8 인코딩으로 저장해야 한다.
또 C/C++ 언어에서 쓰이는 exit() 함수를 D 언어에서 쓰기 위해서는

        import std.c.stdlib;

구문을 소스의 앞부분에 미리 써 놓아야 한다.


소스 파일명: testIfD.d

  1. import std.c.stdio;    // printf 함수 사용을 위해
  2. import std.c.stdlib;    // exit 함수 사용을 위해
  3. import std.conv;        // to! 변환함수 사용을 위해
  4. // 사용법을 컨솔에 보여주는 함수
  5. void printUsing() {
  6.     printf("Using: testIfD [number]\n");
  7.     printf("This determines whether the number is positive or not.\n");
  8. }
  9. int main (string[] args) {
  10.     float val;
  11.     if (args.length != 2) {
  12.         printUsing();
  13.         exit(1);
  14.         return 1;
  15.     }
  16.     // 명령행 인자의 스트링을 가져와서
  17.     // 배정밀도 부동소수점수로 변환하여
  18.     // 변수 val에 저장한다.
  19.     val = to!(float)(args[1]);
  20.     // 변수 val에 저장된 값이 양수인지 음수인지 0인지를
  21.     // 판단하는 if...else... 조건문
  22.     if (val > 0.0)
  23.         printf("%g is a positive number.\n", val);
  24.     else if (val < 0.0)
  25.         printf("%g is a negative number.\n", val);
  26.     else
  27.         printf("%g is zero.\n", val);
  28.     return 0;
  29. }

컴파일> dmd testIfD.d

실행> testIfD
Using: testIfD [number]
This determines whether the number is positive or not.

실행> testIfD 1.234
1.234 is a positive number.

실행> testIfD 1.234
-1.234 is a negative number.

실행> testIfD 0
0 is zero.



Posted by Scripter
,