ํจ์์ ๊ธฐ๋ณธ ๋ชจ์
์ํ์์์ ํจ์์ ๊ฐ์ด, input
ย ,ย output
ย ์ด ์๊ณ ,ย input
ย ์ด ๋ค์ด๊ฐ์ ๋, ์ด๋ค ์์
์ ํ ๋ค,ย output
ย ์ ๋ด๋ณด๋ด๋ ๋ฐฉ์์ผ๋ก ์๋ํ๋ค.
์ฌ๊ธฐ์๋ย input
ย ,ย output
ย ์ ์๋ฌด ์ซ์๋ ๋ฃ์ด์ค๋ ๋์ง๋ง, ์ปดํจํฐ๋ ์ด ์ซ์ ์์ฒด๋ ๋ช
์์ ์ผ๋ก ์จ์ค์ผ ํ๊ธฐ ๋๋ฌธ์, ์ด๋คย input
ย ์ด ๋ค์ด๊ฐ๋์ง, ์์๋๋ย output
ย ์ ์ด๋ค ๋
์์ธ์ง ๋ช
์์ ์ผ๋ก ์จ์ค ํ์๊ฐ ์๋ค.
Function in C++
int iSqrt(int p){ // #1
return p * p; // #2
}
int p
ย :ยinput
ย ํ๋ผ๋ฏธํฐ์ ์๋ฃํ์ integer ์ด์ด์ผ ํ๋ค.int iSqrt
ย :ยoutput
ย ์ ์๋ฃํ์ integer ์ด๋ค.
- ์ด๋ป๊ฒ ์์ฉํ๋์ง ์ ์ด์ฃผ๋ ํจ์์ย
body
ย ์ด๋ค.
Input, output paramater
์ํ์์์ ํจ์์ ๋ค๋ฅด๊ฒย input
ย ,ย output
ย ํ๋ผ๋ฏธํฐ๊ฐ ์์ ์ ์๋ค.
input
ย ํ๋ผ๋ฏธํฐ๊ฐ ์๋ ๊ฒฝ์ฐ
#include <iostream>
int helloworld(void){
cout << "hello world";
return 0;
}
int main(){
helloworld();
}
์ถ๋ ฅ
// helloworld
output
ย ํ๋ผ๋ฏธํฐ๊ฐ ์๋ ๊ฒฝ์ฐ
#include <iostream>
void helloworld(void){
cout << "helloworld";
}
int main(){
helloworld();
}
์ถ๋ ฅ
// helloworld
void
ย ์๋ฃํ์ window ์ด์์ฒด์ ์์๋ง ๊ฐ๋ฅํ๋ค.
Main ํจ์ ์์์ ์ฌ์ฉ
์ ์ธ(Declare)ย ,ย ์ ์(Define)ย ,ย ํธ์ถ(Calling)ย ์ ์ธ๊ณผ์ ์ ๊ฑฐ์น๋ค.
์ ์ธ(Declare)
int iSqrt(int);
main
ย ํจ์๋ก ๋ค์ด๊ฐ๊ธฐ ์ ์, ๋จผ์ ํจ์์ ๋ฐํํ๊ณผ, ํ๋ผ๋ฏธํฐ์ ์๋ฃํ์ด ์จ์ง ํจ์์ ์ํ(prototype) ์ ์ ์ด์ค๋ค. ๋ณ์ ์ด๋ฆ์ ์จ์คํ์์๋ค.
์ ์(Define)
int iSqrt(int p){
return p * p;
}
main
ย ํจ์ ๋ฐ์ ์ด๋ป๊ฒ ์์ฉํ๋์ง ํจ์์ ๋ด์ฉ์ ์ ์ด์ค๋ค. ์ด๋๋ย input
ย ํ๋ผ๋ฏธํฐ๋ก ๋ณ์์ ์ด๋ฆ๊น์ง ์ ์ด์ค์ผ ์ฌ์ฉ๊ฐ๋ฅํ๋ค.
ํธ์ถ(Calling)
y = iSqrt( x );
main
ย ํจ์์์ ๋ถ๋ฌ์ ์ฌ์ฉํ๋ค. ํจ์๋ฅผ ๋๋ฆฌ๊ณ ๋ ๋ฐํ๊ฐ์ด y์ ์ ์ฅ๋๋ค.
์ ์ฒด์ฝ๋ ์์
# include <iostream>
using namespace std;
int sum(int a, int b); // Declare
int main(){
int x, y;
cout << "x ์
๋ ฅ" << endl;
cin >> x;
cout << "y ์
๋ ฅ" << endl;
cin >> y;
cout << sum(x, y) << endl; // Calling
return 0;
}
int sum(int a, int b){ // Define
return a + b;
}
Default Arguments
ํจ์๋ฅผ ํธ์ถํ์ ๋, ์๋ฌด ์ธ์๋ ๋ฃ์ง ์์๋ค๋ฉด, default๋ก ํ๋ผ๋ฏธํฐ๋ฅผ ๋๊ธธ ์ ์๋ค. ์ ์ธํ ๋, ์ธ์๊ฐ๊น์ง ๊ฐ์ด ์ ๋ฌํ๋ฉด ๋๋ค. ๋ํ, input์ด ์ ๊ฒ ๋ค์ด์์ ๊ฒฝ์ฐ, ์ ์ธ์๋ง ์ด๊ธฐ๊ฐ์ผ๋ก ์ค์ ๋๋ค.
# include <iostream>
using namespace std;
int sum(int a, int b); // Defalut Arguments
int main(){
int x, y;
cout << "x ์
๋ ฅ" << endl; // 8
cin >> x;
cout << "y ์
๋ ฅ" << endl; // 5
cin >> y;
cout << sum(x, y) << endl; // 13
cout << sum(x) << endl; // 9
cout << sum() << endl; // 7
return 0;
}
int sum(int a, int b){
return a + b;
}
ํจ์์ ๋์๊ณผ์
#include <iostream>
#include <cmath> // cmath ๋ผ์ด๋ธ๋ฌ๋ฆฌ ํฌํจ
using namespace std;
int main(){
double value;
// ๋ณ์ ํ ๋น
value = 16;
// ๋ฃจํธ ๊ณ์ฐ
double root = sqrt(value);
// ๋ค๋ฅธ ๊ฐ ๊ณ์ฐ ํ ํ ๋น
root = sqrt(100);
}
cmath ๋ ์ํ ํจ์๋ค์ ๋ชจ์๋ ํ์ค c++ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ด๋ค.
์ฐ๋ฆฌ๊ฐ ์ฃผ ๋ชฉ์ ์ ๋๋ ํจ์๋ย main
ย ํจ์์ด๋ค. ์ด๋, ๋ค๋ฅธ ํจ์๋ฅผ ๋ถ๋ฌ์ฌ๋, ์ด๋ค ๋ฐฉ๋ฒ์ผ๋ก ์คํ๋๋์ง ๊ทธ๋ฆผ์ผ๋ก ์ดํด๋ณด์.
main
ย ํจ์๊ฐ ๋์ํ๋ค๊ฐ, ์ค๊ฐ์ย sqrt
ย ๋ฅผ ๋ง๋๋ฉด
๋ง๋ค์ด๋ ๊ทธ ํจ์๋ก ๊ฐ๋ค๊ฐ, ๋ฐํ๊ฐ์ ๋ค์ ๊ฐ์ ธ์ค๊ณ ,
๋ ๋ง๋๋ฉด ๋ค์ ๊ฐ๋ค๊ฐ ๋ฐํ๊ฐ์ ๊ฐ์ ธ์ค๋ ๋ฐฉ์์ผ๋ก ๋์ํ๋ค.
cmath Library
#include <iostream>
- ์ข ๋ฅ