프로그래밍/C++
if...else... 조건문 사용 예제 for C++
Scripter
2008. 2. 19. 16:49
소스 파일명: testIfCPP.cpp
- #include <iostream>
- #include <cmath> // atof() 함수 사용을 위해
- using namespace std; // cout 사용을 위해
- // 사용법 표시 함수
- void printUsing() {
- cout << "Using: testIfCPP [number]\n";
- cout << "This determines whether the number is positive or not.\n";
- }
- // main 함수
- int main(int argc, char *argv[]) {
- float val;
- if (argc != 2) {
- printUsing();
- exit(1);
- return 1;
- }
- // 명령행 인자의 스트링을 가져와서
- // 배정밀도 부동소수점수로 변환하여
- // 변수 val에 저장한다.
- val = atof(argv[1]);
- // 변수 val에 저장된 값이 양수인지 음수인지 0인지를
- // 판단하는 if...else... 조건문
- if (val > 0.0)
- cout << val << " is a positive number.\n";
- else if (val < 0.0)
- cout << val << " is a negative number.\n";
- else
- cout << val << " is zero.\n";
- return 0;
- }
컴파일> cl /GX testIfCPP.cpp
실행> testIfCPP
Using: testIfCPP [number]
This determines whether the number is positive or not.
실행> testIfCPP 1.234
1.234 is a positive number.
실행> testIfCPP 1.234
-1.234 is a negative number.
실행> testIfCPP 0
0 is zero.
※ Ch 5.5를 사용하여 컴피일 과정 없이 소스를 실행시키려면 인클루드문
#incldue <cmath>
을
#incldue <math.h>
로 고치면 된다. 그대신 부동소수점수의 출력이 다소 다르다.
실행> ch testIfCPP.cpp
Using: testIfCPP [number]
This determines whether the number is positive or not.
실행> ch testCPP.cpp 2.7
2.7000 is a positive number.
실행> ch testCPP.cpp -2.7
-2.7000 is a negative number.
실행> ch testCPP.cpp 0
0 is zero.
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.