Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

程式設計 (DOM1034)

第一章:C++的基本輸入輸出、變數與運算式
授課教師:吳浩庠 (111 學年度第二學期)
Disclaimer:

The distribution of these notes without the permission of the Instructor is prohibited.

The notes are only used in this class during the spring semester 2023.

同學們好,歡迎加入 DOM1034。這是一們 C++程式設計基礎課。就讓


我們先用一個簡單的例子來看看如何寫出一個基本程式所需的架構,
這個程式能夠單向的印出一個使用者想印出的東西。

範例 1.1: 印出一個東西 fth =funotion

註解①comment
A

// (1) dolsnof cause the machineto pertormany _ action

#include <stdlib.h> (2) 11 A standard 1ibrary thaf detines general _ , (e. . yfem )
1 purpostfths
9


#include <iostream> (3) enable pogramtooufputsthto the screen _

11 We use the namespale


using namespace std; (4) name std .
fov cout _ ,

averylafer
.
ffn beginsthe executooy_
int main() { (5))main


↳ cout << "Hello C++!"; (6) 1/ show the ( = sfd
" "
coutc_< Hello (t+ ; )
meshage
: :

std : : cout (全名 )


system("pause"); (7) 11 pause the program _
return 0; (8)11 the concept of ffyrverlaler
_

} (9) 111End fovmain _

範例 1.1 輸出結果: Hello C++!


.
Supplementavy 補志
Stafement -
= a unrtof code that hus an

aotion
semico lon ( ; ) is a ferminal statement .

1
分號

程式的運作,是由一連串存取資料、運算以及輸入輸出的過程。回顧
上學期的計概課,我們先學習的是資料的存儲,在這裡,我們用一個
程式來介紹資料存儲,並引入一個重要的觀念:變數宣告。

範例 1. 2: 印出一個變數 Data sforage _ yvaviable


#include <stdlib.h>

#include <iostream>

using namespace std;

int main( ) {
→ (5 ut)

int number = 0; (10) 11 dedare a variable with the type infeger


_ Sinitializeit
_

to O ,

number = 8; (11) hreassigh the value 8 to the variable


_ .

cout << "The number is: "<< number;

system("pause");

return 0;

範例 1. 2 輸出結果:The number is: 8

我們用一個簡單的圖來介紹範例 1. 2 的變數資料存取概念:

A the beginnny


,

number
0
↓→ 1
lZumhoE
althealbey "
(12)
Amemory spanhantinmbin _

OXO3 canonly store ,

2


objecf sfring
變數的觀念 integev floaf ,
.
,

σ
1. 定義:(13) Variable is
alegal mame associated with
_ a value tor
2. 合法的變數命名規則: a memory spac

1 .begin with an alphabet orunderscore ( - )


2 .
nospace or special characters ( . , *. β )
e

(14)
3 . Do not use laeywords ,

_
Keywords list:https://en.cppreference.com/w/cpp/keyword
一些不合法的命名例子:7number, open7-11, mo@ney,…
3. 變數的型態: 216 215 -
~

a. 整數 (int, short, long) ( 16 bifs) : 32968 ~ 32h6g -

short 2 bytes :

Tht : 4 bytes
(15) _
long 8 bytes
=

b. 浮點數 (float, double)


float :
4 bytes
(16) double ; 8 bytes _
c. 字元 (char)
%
Char 1 byte ( e gi . 1

srugle characfer
:

(17)
represents a _
d. 布林 (bool)
bool 1 brf
tine amd fals_
:

(18) repuesents fwo SHafes ,

4. 變數宣告語法

Vartype Vovnane ;

iut VOOmNnm = 310 ;

double myweight = 89 , 2 ;

bool amIaTeacher frue ; ( or = = 1 )


(19) _

3



綜合前頁所學,我們設計一個包含兩種變數型態的計算利率的程式,
也藉由這個程式,我們帶入一個讓程式與使用者互動的語法:cin。

範例 1. 3:

#include <stdlib.h>

#include <iostream>

using namespace std;

int main( ) {

int deposit; .

double rate ;

cout << "Type the amount of the deposit (NTD): "; (20) for data
Prompf user_
tepos
cin >> deposit; (21)read an integer from user into _

cout << "Type the interest rate: ";

cin >> rate; (22)read a decimal ralue from user thto rute _

cout << "Now you have $" << deposit*rate <<" NTD";

system("pause");

return 0;

範例 1. 3 輸出結果:

Type the amount of the deposit (NTD): 100

Type the interest rate: 0.05

Now you have $5 NTD

4
運算式的觀念

在變數的觀念裡,我們了解程式中資料存儲的方法;在範例 1. 3 裡,
我們利用兩個變數做乘法運算,以此為始,接下來我們要學習基本的
運算概念。
_ 时
運算式定義: (23) Epressnn: combonatonofoperands
a

operatong
$ _

運算子:(24) operater :

amonyoperands
an autioy (e g , t
. _ ,
-
, *)

運算元:(25)opevands the objecf of an operufer


: . _

, values varable

一些常用的基本運算子:

a. 指派運算子

Absigumentoperatols: assi} h sth to 5fs leftoperand



eng iutXj thex
c= 10
X ] 11 asigh loto
frrst , then ashigh
8
1 " comput yt
X= □
Y+ 8 to X
the result
y= y+11linoveaseyby 1

(26) _

5


範例 1. 4: 交換兩個變數內的值 (Swap)

#include <stdlib.h>

#include <iostream>

using namespace std;

int main( ) {

int x=8, y=2;

cout << " x is " << x <<" and y is"<<y<<endl;

//endl (std::endl) is to insert a new-line character it


tmiulos ohmttea
//Swap x and y

(27) int tmpill selhare


an alkifionyd _tatihm时
(28) +mp= X ; _

(29) X= Y ; _

(30) Y= temp ; _

cout << "After a swap, x is " << x <<" and y is "<<y<<endl;

system("pause");
Swap X sY wrthout any buffer
.
.

return 0;
Hint :
XOR
}

範例 1. 4 輸出結果:

x is 8 and y is 2

After a swap, x is 2 and y is 8

6

1
哈紹品
" ^ .2 =

b. 算術運算子:+, -, *, /, % σ+
% modulus 三 vefurn the devisioy
remaiudew
(31) _
不等於
c. 比較運算子:>, <, >=, <=,□
==, !=
於 int a = 10 b = 20
cout aa ( a, b } a< ( a ! = b) < ( ac b )
=

0 …
< ( a == b )

否 0

(32) Relational
/ lomparison Operatoon ;
條件
fuue
_
false

logicnl operators helpns


d. 邏輯運算子:&&, ||, !
IIndnOnot 10 / b = 北 ;
Combine simple comparative
statement
int a=
,

,
0
coutcc ( a > b )θ ( a! = b 1 )w
<c

! la > b ) | 1 ( a ! ;

(33) logical Operafors ;


not {
! 沾 _

e. 遞增與遞減運算子:++, --

(34) Increment /
Decrement Opevators : t+ , -
-

atl _
先a =

e gDa
2 =② a 2 先b = = a
③ G=2 ④ G=2 ;
b=
t1 b
.

b att a = a
上b = a b t+ a
再 -- = a
-

a+
-

= =

/a =↑ b : 1/
1 b= ]
1| a
= 3b = 3/ a = 3 b = 2
l a=

f. 複合指定運算子:+=, -=, *=, /=


Compound Assrg nment Operator} : += 1 -
= , *
=
1

/=
at = b ; =) a= atb
e.
g
a* = bj =
) a= a* b
(35) _

g. 位元運算子:處理位元運算,較為進階,在這邊先跳過,知道有
這種運算子就好。

7




𠃌一
C++ 運算子的優先順序:參考連結

https://en.cppreference.com/w/cpp/language/operator_precedence

the fable
remem ber
theorderoburous
,

d 北nof to molke
ube purentheses


e
g atbyc
-
e.

= a+ ( b *c ) - e

v
Priovity Ovder
b / l 2* a) b /2 *a +

|
% 11 女)

Thei order ofoperators


2 ,

+ 1 -
1
(36) , 了 _
compavison
季 ②

從第三頁到現在,我們了解了變數以及各種運算子的基本觀念;我們
也了解,一個運算式的構成,包含了常數,變數,或各種運算子與運
算元組合。接下來我們要討論,當不同型態的變數組合成一個運算式
時,C++所容許的型態轉換。型態轉換在初學者撰寫程式時是容易出錯
的觀念,請務必小心並且理解。

8


型態的轉換

隱性的資料型態轉換:

dala
hasalower Lata type
higher
An operand
isLowverud into a

doubu
type fHoat
)

-
)
long
时 + nt→

convert
(37) Implicit Fye conversan : In some _wes 1 (ff cun

data to anothel antomhthrully


ohe type
顯性的資料型態轉換:

inpbicrllyconverfed
int 1 l0 ]
int =

' chl )
char ch 1
' A
A j of"

=
n based oh the ASC
fo int
int 1 =

inlt chl 5
tofloat
float fl implicitly comerled
;

— int l

f1 =
m □ 六}
s iut / c< f/ j
cout < .

可 不
75 98 了 .

(38) pliiit Type vonversion ,


_
convert drla
we the type manually
flout f2 , f3 = 8 n ;
.

Ciut ) f 3 ;
9
f2 =

cont << f2 << f3


Ʃ ≈
整取 , si ]


範例 1.5: 運算式資料型態轉換的綜合範例
#include <stdlib.h>
#include <iostream>
using namespace std;

型戀以最任yHhwt
int main( ) {

int a = 10;
float b = 4; 10 / 4 215 =

cout << "a/b=" << a/b << endl; (39) 2, 5


,
_
205 = X/(fHoatly
flont ) x / y × fHoat)
=

int x = 10, y =4; (


(tlowt ) /
( y
=
— > iht
cout << "x/y=" << x/y << endl; 2
_

(f|oat) (x /y)
= 2

cout << "(float)x/y=" << (float)x/y << endl; (40) 2 .5


( X/ y ) 州_ -
0

0 .5

6 83 (float) lX/y | /y
=

char ch1='C', ch2 = 'S'; float / 2 /4


(
cout << "ch1 is " << ch1 << ", ch2 is " << ch2 << endl;
out '1 s s
print
' 1
(41)1 _ _
cout << "ch1's code is " << (int)ch1 << endl;
cout<< "ch2's code is " << (int)ch2 << endl;
ont the ASCL ' S 号
+ ( "

(42) 11 _
print
'

6n 83
cout << "ch1*ch2:" << ch1*ch2 << endl;
(43) HASCE ( c) * ASCE( s ) 69 × 53 5561
= =
_
float f = 3.14;
double d = 4.79;
cout << "f*d=" << f*d << endl; (44) fyd hws the type double
cout << "x+f*d=" << x+f*d << endl;
(45) xtfxd huasthetype dubleT _

The htghest order


system("pause");
return 0; the
in
expre 给non
}
10

範例 1.5 輸出結果:

a/b=2.5

x/y=2

(float)x/y = 2.5

ch1 is C, ch2 is S

ch1's code is 67

ch2's code is 83

ch1*ch2: 5561

f*d=15.0406

x+f*d=25.0406

11

範例 1.6: 計算平均的程式
#include <stdlib.h>
#include <iostream>
using namespace std;
int main( ) {
int mid1, mid2, final;
cout << "Please type the scores for two midterms and one final
sequentially:"<< endl ;

cin >> mid1 >> mid2 >> final; (46) it allows users fo _type 3 things sementically ,

(47) float avgj _ ↑

mid 1 tmind +fma 1 )/


(48) (float ) (
2
_ 3

cout << "The average is: " << avg << endl;
system("pause");
return 0;
}

範例 1.6 輸出結果:
Please type the scores for two midterms and one final sequentially:
65 80 90
The average is: 78.3333

Queston 5 : X
) / 3 wolc ?
Afl 48 ) , cantmrdlthid 2 tfinal
( (tlontlmidlthidzthid 3 /13
? 0有 个变取是loct
( midi + mid 2 +final / / (f / oat ) 3 ?0 就可以
(49) _
v Cmidl thid Ltfmal ) / 3 0 . 0
12
認成 fHont


本章節的最後,我們要介紹一個有用的數學函式庫 cmath,用以做出較
為複雜的數學運算。另外我們也要介紹一組最初階的條件式,目的是
為了在下一個章節開始前做熱身。利用這些東西,我們可以從頭到尾
複習本章所學過的觀念,也可以開始撰寫一些簡單而有趣的程式了。

在這邊和同學說明,我們尚未教到函式或物件的觀念,所以請先將數
學函式庫聯想成如我們範例 1.1 所聯想的 iostream 百寶箱,當時我們想
像 iostream 裡面包含 cin\cout 工具,利用這些工具,我們能夠做簡單的
輸入輸出。現在我們將 cmath 聯想成一個裝有很多數學運算工具的百寶
箱,利用這些工具,我們可以做很多運算,這些工具的英文解釋如下
連結:

http://www.cplusplus.com/reference/cmath/

在這邊我們會介紹取開根號的工具,至於其他不同的工具,請同學試
著打開上面的連結,點進不同的工具名稱,裡面有詳盡的解釋與程式
範例。慢慢的,同學也要開始學習利用線上資源找尋資料。

13
範例 1.7: 開根號 I
#include <stdlib.h>
#include <iostream>
#include <cmath> (50) enab 做 touse
_ some
useful math tool
using namespace std;
pograms
int main( ) {
float x, float_ans;
cout << "Type float x:" <<endl;
cin >> x;
int y, int_ans;
cout << "Type int y:" <<endl;
cin >> y;

int_ans = sqrt(x);
float_ans = sqrt(x);
(51) / sqrt ( 215 ) =
1158114 _

cout << "The square root of float x is: " << int_ans << "(int), " <<
float_ans << "(float)" << endl;
M )
18 (52))ans
int
← - 1
=
sqrt 1205 _

1 58114
.
← 1|float -
ans = sqrt (205 )
int_ans = sqrt(y);
float_ans = sqrt(y);
cout << "The square root of int y is: " << int_ans << "(int), " <<
float_ans << "(float)" << endl;
sqrtly Sqrt (2) = 1 414 _
(53) 11
!
= .

+nt _ =
mg =
sqlelz )

int float
system("pause"); _ uns = sqrt 12 ) = 1 .
414
return 0;
}

14

範例 1.7 輸出結果:

Type float x:

2.5

Type int y:

2.5

The square root of float x is: 1(int), 1.58114(float)

The square root of int y is: 1(int), 1.41421(float)

結束了嗎?其實還沒,若不考慮虛數,我們知道對負數開平方根是無效
的,我們加入一個簡單的條件式,告訴使用者,程式只能對大於等於
零的數開根號。這個簡單的條件式在程式設計裡也被稱為控制敘述
(control statements)。控制敘述讓程式設計變得多彩多姿,也是初學者
所面對的第一個較為複雜的結構。利用這個例子做結尾,我們將在下
個章節深入介紹各種不同的控制敘述。

15
範例 1.8: 開根號 II
#include <stdlib.h>
#include <iostream>
#include <cmath>
using namespace std;
int main( ) {
float x, float_ans;
cout << "Type float x:" <<endl;
cin >> x;
if(x >=0 ){
(54) 1Hif X20 1 wecompute _ Gqrtly
float_ans = sqrt(x);
cout << "The square root of float x is: "<< float_ans <<
"(float)" << endl;
}
else{
(55) Nif Xco 1 we show the evror _
message
cout << "x cannot be negative!";
}

system("pause");
return 0;
}

16
範例 1.8 輸出結果:

第一種:

Type float x:

-2.5

x cannot be negative!

第二種:

Type float x:

2.5

The square root of float x is: 1.58114(float)

17

You might also like