U E D R , A S I H C RSS

AcceleratedC++/Chapter2

Chapter 2

μ€‘μš” μ†ŒμŠ€

~cpp 
#include <iostream>
#include <string>

// say what standard-library names we use
using std::cin;
using std::cout;
using std::string;
using std::endl;

int main() {
	// ask for person's name
	cout << "Please enter your first name: ";

	// read the name
	string name;
	cin >> name;
	
	// build the message that we intend to write
	const string greeting = "Hello, " + name + "!";
	
	// the number of blacks surrounding the greeting
	const int pad = 1;

	// the number of rows and columns to write
	const int rows = pad * 2 + 3;
	const string::size_type cols = greeting.size() + pad * 2 + 2;

	// write blank line to separate the output from the input
	cout << endl;

	// write rows 
	// invariant: we have written r rows so far
	for (int r = 0; r != rows ; ++r) {
		string::size_type c = 0;

		// invariant: we have written c
		while (c != cols) {

			// is it time to write the greeting?
			if (r == pad + 1 && c == pad + 1) {
				cout << greeting;
				c += greeting.size();
			} else {

				// are we on the border?
				if (r == 0 || r == rows - 1 ||
					c == 0 || c == cols - 1)
					cout << "*";
				else
					cout << " ";
				++c;
			}
		}
		cout << endl;
	}

	return 0;
}
----

질문

책에 보면 (21νŽ˜μ΄μ§€),
~cpp 
// invariant : we have written r rows so far
int r = 0;
// setting r to 0 makes the invariant true
while( r != rows )
{
 // we can assume that the invariant is true here
 // writing a row of output makes the invariant false
 std::cout << std::endl;
 // incrementing r makes the invariant true again
 ++r;
}
// we can conclude that the invariant is true here
 
μ½”λ“œμ˜ λ§ˆμ§€λ§‰ λΆ€λΆ„μ—μ„œ invariant κ°€ λ‹€μ‹œ true 둜 λ˜λŠ”κ²ƒμΌκΉŒμš”.? invariant κ°€ 무엇인지 아직 κ°œλ…μ΄ μž‘νžˆμ§€ μ•ˆμ•„μ„œ. -_-a - μž„μΈνƒ
μ €λŠ” μ΄μ œμ„œμ•Ό AcceleratedC++을 보고 μžˆλŠ”λ°μš”. loop invariantλž€ r번 μˆ˜ν–‰ν–ˆλ‹€λΌλŠ” 것을 λ§ν•˜μ§€ μ•Šμ„κΉŒμš”?
r이 μ²˜μŒμ— 0μ΄λ‹ˆκΉŒ while에 μ§„μž…ν•˜λŠ” μ‹œμ μ—λŠ” cout을 0번 μˆ˜ν–‰ν–ˆμ„ν…Œκ³  λ”°λΌμ„œ r = 0, μˆ˜ν–‰νšŸμˆ˜ = 0 λ”°λΌμ„œ λΆˆλ³€μ‹μ€ μ°Έ
r이 0이고 cout을 ν•œλ²ˆ μˆ˜ν–‰ν•˜λ©΄ r = 0, μˆ˜ν–‰νšŸμˆ˜ = 1 λ”°λΌμ„œ λΆˆλ³€μ‹ 거짓
while의 λ§ˆμ§€λ§‰ 전에 r을 1 μ¦κ°€μ‹œν‚€λ€λ‘œ... r = 1, μˆ˜ν–‰νšŸμˆ˜ = 1 λ”°λΌμ„œ λΆˆλ³€μ‹ μ°Έ
λ”°λΌμ„œ while의 쑰건식 λΉ„κ΅μ—μ„œλ„ r = 1, μˆ˜ν–‰νšŸμˆ˜ =1 λ”°λΌμ„œ λΆˆλ³€μ‹ μ°Έ...
또 cout 을 μˆ˜ν–‰ν•˜κ²Œ λœλ‹€λ©΄ r = 1, μˆ˜ν–‰νšŸμˆ˜ = 2λ‹ˆκΉŒ λΆˆλ³€μ‹ 거짓...
μ˜ˆμ „μ— http://www.pragmaticprogrammer.com/ppllc/papers/1998_05.html μ—μ„œ invariantsλΌλŠ” 말이 λ‚˜μ™”μ—ˆλŠ”λ° 같은 κ°œλ…μœΌλ‘œ μƒκ°ν•˜λ©΄ λ λ €λ‚˜ γ…‘,.γ…‘; --Benghun

----
μ–΄μ§Έμ„œ C의 λ£¨ν”„λŠ”0λΆ€ν„°? 인지... κ°„λ‹¨ν•œ λŒ€λ‹΅μ΄ λ‚˜μ™€ μžˆλ”κ΅°μš”. - 톱아보닀

----
AcceleratedC++
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:22:25
Processing time 0.0209 sec