소스 파일명: testArgumentsCPP.cpp
  1. #include <iostream>  // cout 함수와 endl 문자의사용을 위해
  2. #include <cmath>     // atof 함수 사용을 위해
  3. using namespace std;
  4. // argc는 명령행 인자 개수, argv는 명령행 인자 문자열의 배열
  5. int main(int argc, char *argv[]) {
  6.     int i;
  7.     double sum = 0.0;    // 초기화
  8.     // 명령행 인자(command-line argument) 개수 출력
  9.     cout << "Count of arguments: " << argc << endl;
  10.     for (i = 0; i < argc; i++) {
  11.         // 스트링을 배정밀도 부동소수점수로 변환하여 누적
  12.         sum += atof(argv[i]);
  13.     }
  14.     // 배정밀도 부동소수점수 값을 cout로 출력
  15.     cout << "The sum of arguments is " << sum << endl;
  16.     return 0;
  17. }


컴파일> cl -GX testArgumentsCPP.cpp

실행> testArgumentsCPP 1 2 3 4
Count of arguments: 5
The sum of arguments is 10

실행> testArgumentsCPP 1 2 3 4.1
Count of arguments: 5
The sum of arguments is 10.1





Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,


소스 파일명: testArguments.c

  1. #include <stdio.h>   // printf 함수 사용을 위해
  2. #include <math.h>    // atof 함수 사용을 위해
  3. // argc는 명령행 인자 개수, argv는 명령행 인자 문자열의 배열
  4. int main(int argc, char *argv[]) {
  5.     int i;
  6.     double sum = 0.0;    // 초기화
  7.     // 명령행 인자(command-line argument) 개수 출력
  8.     printf("Count of arguments: %d\n", argc);
  9.     for (i = 0; i < argc; i++) {
  10.         // 스트링을 배정밀도 부동소수점수로 변환하여 누적
  11.         sum += atof(argv[i]);
  12.     }
  13.     // 배정밀도 부동소수점수 값을 %g로 출력
  14.     printf("The sum of arguments is %g\n", sum);
  15.     return 0;
  16. }


컴파일> cl testArguments.c

실행> testArguments 1 2 3 4
Count of arguments: 5
The sum of arguments is 10

실행> testArguments 1 2 3 4.2
Count of arguments: 5
The sum of arguments is 10.2


 


Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,


Groovy 언어에서 args는 예약어이다. 이는 Java 언어에서 main 메소드 정의 구문
         public static void main(String[] args) {
             ..............
         }
에서 매개변수(파라미터) args와 동일한 기능을 같는다. Java 언어라면 이 main 매소드 정의 구문에서 다른 변수로 바꾸어도 되지만, Groovy 언어에서는 args가 에약어로 되어 있으므로 일반 변수 선언시 변수명을 args로 하지 않는 것이 좋다.
 
부분 문자열(스트링)을 구하기 위햐여 범위(range) 연산자 ..<를 사용하였다. 이 연산자는 Ruby 언어의 ...와 동일한 연산자로서 ..와 다른 것은 범위의 마지막 값이 제외된다는 것이다.


소스 파일명: testArguments.groovy

  1. double sum = 0.0
  2. println("Count of arguments: " + args.length)
  3. for (int i = 0; i < args.length; i++) {
  4.     sum += Double.parseDouble(args[i])
  5. }
  6. String strSum = "" + sum
  7. if (strSum.endsWith(".0"))
  8.     strSum = strSum[0..<(strSum.length() - 2)]
  9. println("The sum of arguments is " + strSum)


실행> groovy testArguments.groovy 1 2 3 4
Count of arguments: 4
The sum of arguments is 10


실행> groovy testArguments.groovy 1 2 3 4.5
Count of arguments: 4
The sum of arguments is 10.5





Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,