Presentation is loading. Please wait.

Presentation is loading. Please wait.

Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 3 수식과.

Similar presentations


Presentation on theme: "Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 3 수식과."— Presentation transcript:

1 Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 3 수식과 입출력

2 Chapter 3 Starting Out with C++: Early Objects 5/e slide 2 © 2006 Pearson Education. All Rights Reserved Topics 3.1 cin 객체 3.2 수학 계산식 3.3 묵시적 형변환 3.4 명시적 형변환 3.5 오브플로, 언더플로 3.6 이름 붙인 상수

3 Chapter 3 Starting Out with C++: Early Objects 5/e slide 3 © 2006 Pearson Education. All Rights Reserved Topics ( 계속 ) 3.7 다중 배정과 결합 배정 3.8 출력 포맷 3.9 문자와 문자열 객체의 처리 3.10 C- 문자열의 사용 3.11 더 많은 수학 라이브러리 함수들 3.12 파일의 소개

4 Chapter 3 Starting Out with C++: Early Objects 5/e slide 4 © 2006 Pearson Education. All Rights Reserved 3.1 cin 객체 표준 입력 객체 cout 과 같이 iostream 파일 요구 키보드로부터 입력시 사용 가끔 사용자에게 프롬트트 ( 지시메시지 ) 를 출력하는 cout 과 같이 사용된다. 스트림 추출연산자 >> 를 사용하여 자료가 읽혀진다. 입력된 자료는 하나 이상의 변수에 저장된다. #include

5 Chapter 3 Starting Out with C++: Early Objects 5/e slide 5 © 2006 Pearson Education. All Rights Reserved cin 객체 사용자 입력은 키보드에서 입력 버퍼로 문자들로서 저장된다. cin 은 변수와 일치하는 타입의 자료로 변환한다. int height; cout << "How tall is the room? "; cin >> height;

6 Chapter 3 Starting Out with C++: Early Objects 5/e slide 6 © 2006 Pearson Education. All Rights Reserved cin 객체 여러 개의 값을 입력할 수 있다. cin >> height >> width; 키보드로부터 입력된 여러 값은 스페이스나 [Enter] 에 의해 구분되어야 한다. 순서가 중요하다. 처음 값은 처음 변수에 다음 값은 다음 변수에 저장된다.

7 Chapter 3 Starting Out with C++: Early Objects 5/e slide 7 © 2006 Pearson Education. All Rights Reserved 3.2 수학 계산식 계산식은 상수, 변수 또는 연산자와 결합된 상수와 변수의 조합일 수 있다. 다중 수학 계산 연산자를 사용하여 복잡한 계산식을 만들 수 있다. 수학 계산식 예 2 height a + b / c

8 Chapter 3 Starting Out with C++: Early Objects 5/e slide 8 © 2006 Pearson Education. All Rights Reserved 수학 계산식 사용 배정문에서 또는 cout 과 함께 다른 타입의 문장에서 사용될 수 있다. Examples: area = 2 * PI * radius; cout << "border is: " << (2*(l+w)); This is an expression These are expressions

9 Chapter 3 Starting Out with C++: Early Objects 5/e slide 9 © 2006 Pearson Education. All Rights Reserved 연산의 우선순서 In an expression with > 1 operator, evaluate in this order - (unary negation) in order, left to right * / % in order, left to right + - in order, left to right In the expression 2 + 2 * 2 – 2, Do first Do last Do next Evaluate 1st Evaluate 2nd Evaluate 3rd

10 Chapter 3 Starting Out with C++: Early Objects 5/e slide 10 © 2006 Pearson Education. All Rights Reserved 연산자의 결합규칙 (Associativity) - (unary negation) associates right to left * / % + - all associate left to right parentheses ( ) can be used to override the order of operations 2 + 2 * 2 – 2 = 4 (2 + 2) * 2 – 2 = 6 2 + 2 * (2 – 2) = 2 (2 + 2) * (2 – 2) = 0

11 Chapter 3 Starting Out with C++: Early Objects 5/e slide 11 © 2006 Pearson Education. All Rights Reserved 산술수식 곱하기 : 곱셈 연산자 * Area = lw is written as Area = l * w; 지수연산 : Area = s 2 is written as Area = pow(s, 2); 연산 순서를 변경하기 위해 소괄호 () 가 필요 m = (y2-y1)/(x2-x1);

12 Chapter 3 Starting Out with C++: Early Objects 5/e slide 12 © 2006 Pearson Education. All Rights Reserved 3.3 묵시적 형변환 Operations are performed between operands of the same type If not of the same type, C++ will automatically convert one to be the type of the other This can impact the results of calculations

13 Chapter 3 Starting Out with C++: Early Objects 5/e slide 13 © 2006 Pearson Education. All Rights Reserved 자료형의 계층 Highest Lowest Ranked by largest number they can hold long double double float unsigned long long unsigned int int

14 Chapter 3 Starting Out with C++: Early Objects 5/e slide 14 © 2006 Pearson Education. All Rights Reserved 자료형의 강제변환 강제변환 (Coercion): 피연산자의 자료형을 다른 자료형으로 자동 변환 승격 (Promotion): converts to a higher type 강등 (Demotion): converts to a lower type

15 Chapter 3 Starting Out with C++: Early Objects 5/e slide 15 © 2006 Pearson Education. All Rights Reserved 강제 변환 규칙 1) char, short, unsigned short are automatically promoted to int 2)When operating on values of different data types, the lower one is promoted to the type of the higher one. 3)When using the = operator, the type of expression on right will be converted to type of variable on left

16 Chapter 3 Starting Out with C++: Early Objects 5/e slide 16 © 2006 Pearson Education. All Rights Reserved 3.4 명시적 형변환 Also called type casting( 자료형 캐스팅 ) Used for manual data type conversion Format static_cast (expression) Example: cout (65); // Displays 'A'

17 Chapter 3 Starting Out with C++: Early Objects 5/e slide 17 © 2006 Pearson Education. All Rights Reserved 형 캐스팅 예 char ch = 'C'; cout << ch << " is stored as " (ch); gallons = static_cast (area/500); avg = static_cast (sum)/count;

18 Chapter 3 Starting Out with C++: Early Objects 5/e slide 18 © 2006 Pearson Education. All Rights Reserved 형 캐스팅의 예전 방법 double Volume = 21.58; int intVol1, intVol2; intVol1 = (int) Volume; // C-style // cast intVol2 = int (Volume); //Prestandard // C++ style // cast static_cast is current standard

19 Chapter 3 Starting Out with C++: Early Objects 5/e slide 19 © 2006 Pearson Education. All Rights Reserved 3.5 오브플로, 언더플로 Occurs when assigning a value that is too large (overflow) or too small (underflow) to be held in a variable Variable contains value that is ‘wrapped around’ the set of possible values

20 Chapter 3 Starting Out with C++: Early Objects 5/e slide 20 © 2006 Pearson Education. All Rights Reserved 오브플로 예 // Create a short int initialized to // the largest value it can hold short int num = 32767; cout << num; // Displays 32767 num = num + 1; cout << num; // Displays -32768

21 Chapter 3 Starting Out with C++: Early Objects 5/e slide 21 © 2006 Pearson Education. All Rights Reserved 오브플로, 언더플로 다루기 Different systems handle the problem differently. They may –display a warning / error message –display a dialog box and ask what to do – stop the program – continue execution with the incorrect value

22 Chapter 3 Starting Out with C++: Early Objects 5/e slide 22 © 2006 Pearson Education. All Rights Reserved 3.6 이름 붙인 상수 상수변수 프로그램 실행동안 값이 변경될 수 없는 변수 Used for representing constant values with descriptive names const double TAX_RATE = 0.0675; const int NUM_STATES = 50; 주로 대문자 사용

23 Chapter 3 Starting Out with C++: Early Objects 5/e slide 23 © 2006 Pearson Education. All Rights Reserved const vs. #define #define 지시자 – C-style of naming constants #define NUM_STATES 50 – 전처리기에 의해 해석 –Does not occupy a memory location like a constant variable defined with const –Instead, causes a textual substitution to occur. In above example, every occurrence in program of NUM_STATES will be replaced by 50 no ; goes here

24 Chapter 3 Starting Out with C++: Early Objects 5/e slide 24 © 2006 Pearson Education. All Rights Reserved 3.7 다중 배정과 결합 배정 다중배정 : The assignment operator ( = ) can be used > 1 time in an expression x = y = z = 5; Associates right to left x = (y = (z = 5)); Done Done Done 3 rd 2 nd 1 st

25 Chapter 3 Starting Out with C++: Early Objects 5/e slide 25 © 2006 Pearson Education. All Rights Reserved 결합 배정 Applies an arithmetic operation to a variable and assigns the result as the new value of that variable 연산자 : += -= *= /= %= 예 : sum += amt; is short for sum = sum + amt;

26 Chapter 3 Starting Out with C++: Early Objects 5/e slide 26 © 2006 Pearson Education. All Rights Reserved 예 x += 5; means x = x + 5; x -= 5; means x = x – 5; x *= 5; means x = x * 5; x /= 5; means x = x / 5; x %= 5; means x = x % 5; The entire right hand side is evaluated before the combined assignment operation is done. x *= a + b; means x = x * (a + b);

27 Chapter 3 Starting Out with C++: Early Objects 5/e slide 27 © 2006 Pearson Education. All Rights Reserved 3.8 출력 포맷 Can control how output displays for numeric and string data – 크기 – 위치 – 자리수 Requires iomanip header file #include

28 Chapter 3 Starting Out with C++: Early Objects 5/e slide 28 © 2006 Pearson Education. All Rights Reserved 스트림 조정자 출력 필드의 속성을 제어 Some affect just the next value displayed –setw(x) : Print in a field at least x spaces wide. Use more spaces if specified field width is not big enough.

29 Chapter 3 Starting Out with C++: Early Objects 5/e slide 29 © 2006 Pearson Education. All Rights Reserved 스트림 조정자 Some affect values until changed again –fixed : Use decimal notation (not E-notation) for floating-point values. –setprecision(x) : When used with fixed, print floating-point value using x digits after the decimal. Without fixed, print floating-point value using x significant digits. –showpoint : Always print decimal for floating-point values. –left, right : left-, right justification of value

30 Chapter 3 Starting Out with C++: Early Objects 5/e slide 30 © 2006 Pearson Education. All Rights Reserved 조정자 사용 예 const float e = 2.718; float price = 25.0; Displays cout << setw(8) << e << endl; ^^^2.718 cout << left << setw(8) << e << endl; 2.718^^^ cout << setprecision(2); cout << e << endl; 2.7 cout << fixed << e << endl; 2.72 cout << setw(6) << price; 25.00^

31 Chapter 3 Starting Out with C++: Early Objects 5/e slide 31 © 2006 Pearson Education. All Rights Reserved 3.9 문자와 문자열 객체의 처리 char : 하나의 문자를 담는다. string : 일련의 문자열을 담는다. 둘 다 배정문에서 사용될 수 있다. 둘 다 cout 과 << 를 사용하여 출력될 수 있다.

32 Chapter 3 Starting Out with C++: Early Objects 5/e slide 32 © 2006 Pearson Education. All Rights Reserved 문자 입력 하나의 문자를 키보드로부터 읽을 때, char ch; cin >> ch; // Reads in any non-blank char cin.get(ch); // Reads in any char cin.ignore() // Skips over next char in // the input buffer

33 Chapter 3 Starting Out with C++: Early Objects 5/e slide 33 © 2006 Pearson Education. All Rights Reserved 문자열 입력 스트링 객체에 읽을 때, string str; cin >> str; // Reads in a string // with no blanks getline(cin, str); // Reads in a string // that may contain // blanks

34 Chapter 3 Starting Out with C++: Early Objects 5/e slide 34 © 2006 Pearson Education. All Rights Reserved 문자열 연산자 = 는 스트링에 값을 배정한다. string words; words = "Tasty "; + Joins two strings together string s1 = "hot", s2 = "dog"; string food = s1 + s2; // food = "hotdog" += Concatenates a string onto the end of another one words += food; // words now = "Tasty hotdog"

35 Chapter 3 Starting Out with C++: Early Objects 5/e slide 35 © 2006 Pearson Education. All Rights Reserved 프로그램 3-22 // This program illustrates using the getline function // to read character data into a string object. #include using namespace std; int main() { string name; string city; cout << "Please enter your name." << endl; getline(cin, name); cout << "Please enter the city you live in." << endl; getline(cin, city); cout << "Hello, " << name << endl; cout << "You live in " << city << endl; return 0; }

36 Chapter 3 Starting Out with C++: Early Objects 5/e slide 36 © 2006 Pearson Education. All Rights Reserved 프로그램 3-23( 오류 ) // This program illustrates a problem that can occur if // cin is used to read character data into a string object. #include using namespace std; int main() { string name; string city; cout << "Please enter your name." << endl; cin >> name; cout << "Please enter the city you live in." << endl; cin >> city; cout << "Hello, " << name << endl; cout << "You live in " << city <<endl; return 0; } John Doe

37 Chapter 3 Starting Out with C++: Early Objects 5/e slide 37 © 2006 Pearson Education. All Rights Reserved 프로그램 3-24 // This program reads a single character into a char variable. #include using namespace std; int main() { char ch; cout << "Type a character and press Enter: "; cin >> ch; cout << "You entered " << ch << endl; return 0; }

38 Chapter 3 Starting Out with C++: Early Objects 5/e slide 38 © 2006 Pearson Education. All Rights Reserved 프로그램 3-25 // This program uses cin.get() to pause the program. #include using namespace std; int main() { char ch; cout << "This program has paused. Press Enter to continue."; cin.get(ch); cout << "Thank you!" << endl; return 0; }

39 Chapter 3 Starting Out with C++: Early Objects 5/e slide 39 © 2006 Pearson Education. All Rights Reserved 3.10 C- 문자열의 사용 C- 문자열은 문자 배열로 저장된다. 프로그래머는 C- 문자열 정의 시 최대 크기를 반드시 지정하여야 한다. const int SIZE = 5; char temp[SIZE] = "Hot"; 문자열의 끝을 지시하기 위해 널 문자 ( 널 종결자 : \0 ) 가 문자열의 끝에 들어간다. Programmer must make sure array is big enough for desired use; temp can hold up to 4 characters plus the \0. H o t \0

40 Chapter 3 Starting Out with C++: Early Objects 5/e slide 40 © 2006 Pearson Education. All Rights Reserved C- 문자열의 입력 C- 문자열에 읽어오기 const int SIZE = 10; char Cstr[SIZE]; cin >> Cstr; // Reads in a C-string with no // blanks. Will write past the // end of the array if input string // is too long. cin.getline(Cstr, 10); // Reads in a C-string that may // contain blanks. Ensures <= 9 // chars are read in.

41 Chapter 3 Starting Out with C++: Early Objects 5/e slide 41 © 2006 Pearson Education. All Rights Reserved C- 문자열의 초기화 vs. 배정 C- 문자열도 문자열과 같이 정의 시 초기화될 수 있다. const int SIZE = 10; char month[SIZE] = "April"; However, a C-string cannot later be assigned a value using the = operator; you must use the strcpy() function char month[SIZE]; month = "April" // wrong! strcpy(month, "April"); //correct #include

42 Chapter 3 Starting Out with C++: Early Objects 5/e slide 42 © 2006 Pearson Education. All Rights Reserved 3.11 더 많은 수학 라이브러리 함수들 cmath 헤드 파일 요구. double 매개변수를 요구하고 double 을 반환한다. 함수 예 abs Absolute value sin Sine cos Cosine tan Tangent sqrt Square root log Natural (e) log

43 Chapter 3 Starting Out with C++: Early Objects 5/e slide 43 © 2006 Pearson Education. All Rights Reserved Cmath 함수 사용 예 ( 프로그램 3-31) // This program inputs the lengths of the two sides of a right // triangle, then calculates and displays the length of the hypotenuse. #include #include // Needed to use the sqrt function using namespace std; int main() { double a, b, c; cout << "Enter the length of side A: "; cin >> a; cout << "Enter the length of side B: "; cin >> b; c = sqrt(pow(a, 2.0) + pow(b, 2.0)); cout << "The length of the hypotenuse is "; cout << c << endl; return 0; }

44 Chapter 3 Starting Out with C++: Early Objects 5/e slide 44 © 2006 Pearson Education. All Rights Reserved 더 많은 수학 라이브러리 함수들 cstdlib 헤드 파일 요구 rand –Returns a random number between 0 and the largest int the computer holds –With the same seed, will yield same sequence of numbers each time program is run srand(x) –Initializes random number generator with unsigned int x

45 Chapter 3 Starting Out with C++: Early Objects 5/e slide 45 © 2006 Pearson Education. All Rights Reserved 난수 발생기 함수 사용 예 // This program demonstrates random numbers. 프로그램 3-32 #include using namespace std; int main() { unsigned seed; cout << "Enter a seed value: "; cin >> seed; srand (seed); // Call srand to set a "seed" before // any random numbers can be generated cout << rand () << endl; // Now generate and print 3 random numbers cout << rand () << endl; return 0; } 실행 결과 : P. 136-137 참고

46 Chapter 3 Starting Out with C++: Early Objects 5/e slide 46 © 2006 Pearson Education. All Rights Reserved 난수 발생기 함수 사용 예 y = 1 + rand() % maxRange; dice = 1 + rand() % 6; 실습 : 주사위 2 개를 던져 나오는 임의의 수의 합을 출력하시오.

47 Chapter 3 Starting Out with C++: Early Objects 5/e slide 47 © 2006 Pearson Education. All Rights Reserved 3.12 파일의 소개 프로그램 입력을 위해 키보드 대신에 파일을 사용 프로그램 출력을 위해 화면 대신에 파일을 사용 파일  보조기억장치 ( 디스크 ) 에 저장 파일은 프로그램 실행될 때 자료를 보존

48 Chapter 3 Starting Out with C++: Early Objects 5/e slide 48 © 2006 Pearson Education. All Rights Reserved 파일 사용 시에 요구되는 것 1.Include the fstream header file 2.Define a file stream object ifstream for input from a file ifstream inFile; ofstream for output to a file ofstream outFile; #include

49 Chapter 3 Starting Out with C++: Early Objects 5/e slide 49 © 2006 Pearson Education. All Rights Reserved 파일 열기 3.Open the file Use the open member function inFile.open("inventory.dat"); outFile.open("report.txt"); Filename may include drive, path info. Output file will be created if necessary; existing output file will be erased first Input file must exist for open to work

50 Chapter 3 Starting Out with C++: Early Objects 5/e slide 50 © 2006 Pearson Education. All Rights Reserved 파일 사용하기 4.Use the file Can use output file object and << to send data to a file outFile << "Inventory report"; Can use input file object and >> to copy data from file to variables inFile >> partNum; inFile >> qtyInStock >> qtyOnOrder;

51 Chapter 3 Starting Out with C++: Early Objects 5/e slide 51 © 2006 Pearson Education. All Rights Reserved 파일 닫기 5.Close the file Use the close member function inFile.close(); outFile.close(); Don’t wait for operating system to close files at program end –May be limit on number of open files –May be buffered output data waiting to be sent to a file

52 Chapter 3 Starting Out with C++: Early Objects 5/e slide 52 © 2006 Pearson Education. All Rights Reserved 파일 사용하기 예 ( 파일 출력 ) // This program uses the << operator to write information to a file. 프로그램 3-33 #include #include // Needed to use files using namespace std; int main() { ofstream outputFile; outputFile.open("demofile.txt"); cout << "Now writing information to the file.\n"; // Write 3 great names to the file outputFile << "Bach\n"; outputFile << "Beethoven\n"; outputFile << "Mozart\n"; // Close the file outputFile.close(); cout << "Done.\n"; return 0; }

53 Chapter 3 Starting Out with C++: Early Objects 5/e slide 53 © 2006 Pearson Education. All Rights Reserved 파일 사용하기 예 ( 파일 입력 ) // This program uses the >> operator to read information from a file. 프로그램 3-34 #include #include // Needed to use files #include using namespace std; int main() { ifstream inFile; string name; inFile.open("demofile.txt"); cout << "Reading information from the file.\n\n"; inFile >> name; // Read name 1 from the file cout << name << endl; // Display name 1 inFile >> name; // Read name 2 from the file cout << name << endl; // Display name 2 inFile >> name; // Read name 3 from the file cout << name << endl; // Display name 3 inFile.close(); // Close the file cout << "\nDone.\n"; return 0; }

54 Chapter 3 Starting Out with C++: Early Objects 5/e slide 54 © 2006 Pearson Education. All Rights Reserved 파일 사용하기 예 ( 파일 입출력 ) // This program uses the >> operator to read data from a file. // Notice that, as with cin, more than one value can be read in from // a file with a single statement. #include using namespace std; int main() { ifstream inFile; int length, width; inFile.open("dimensions.txt"); cout << "Reading dimensions of 4 rectangles from the file.\n\n"; // Process rectangle 1 inFile >> length >> width; cout << "Area of rectangle 1: " << length * width << endl; // Process rectangle 2 inFile >> length >> width; cout << "Area of rectangle 2: " << length * width << endl; // Process rectangle 3 inFile >> length >> width; cout << "Area of rectangle 3: " << length * width << endl; // Process rectangle 4 inFile >> length >> width; cout << "Area of rectangle 4: " << length * width << endl; // Close the file inFile.close(); cout << "Done.\n"; return 0; }

55 Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 3 Expressions and Interactivity


Download ppt "Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 3 수식과."

Similar presentations


Ads by Google