Professional Documents
Culture Documents
Ç Ä Ç Ï C Çåºæ È Å È Åºãè®æ Èéç®å
Ç Ä Ç Ï C Çåºæ È Å È Åºãè®æ Èéç®å
第一章: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.
註解①comment
A
#include <stdlib.h> (2) 11 A standard 1ibrary thaf detines general _ , (e. . yfem )
1 purpostfths
9
獼
#include <iostream> (3) enable pogramtooufputsthto the screen _
averylafer
.
ffn beginsthe executooy_
int main() { (5))main
↳
↳ cout << "Hello C++!"; (6) 1/ show the ( = sfd
" "
coutc_< Hello (t+ ; )
meshage
: :
aotion
semico lon ( ; ) is a ferminal statement .
1
分號
丶
程式的運作,是由一連串存取資料、運算以及輸入輸出的過程。回顧
上學期的計概課,我們先學習的是資料的存儲,在這裡,我們用一個
程式來介紹資料存儲,並引入一個重要的觀念:變數宣告。
#include <iostream>
int main( ) {
→ (5 ut)
to O ,
system("pause");
return 0;
我們用一個簡單的圖來介紹範例 1. 2 的變數資料存取概念:
A the beginnny
片
,
number
0
↓→ 1
lZumhoE
althealbey "
(12)
Amemory spanhantinmbin _
2
一
一
objecf sfring
變數的觀念 integev floaf ,
.
,
σ
1. 定義:(13) Variable is
alegal mame associated with
_ a value tor
2. 合法的變數命名規則: a memory spac
(14)
3 . Do not use laeywords ,
_
Keywords list:https://en.cppreference.com/w/cpp/keyword
一些不合法的命名例子:7number, open7-11, mo@ney,…
3. 變數的型態: 216 215 -
~
short 2 bytes :
Tht : 4 bytes
(15) _
long 8 bytes
=
srugle characfer
:
(17)
represents a _
d. 布林 (bool)
bool 1 brf
tine amd fals_
:
4. 變數宣告語法
Vartype Vovnane ;
double myweight = 89 , 2 ;
3
」
日
一
綜合前頁所學,我們設計一個包含兩種變數型態的計算利率的程式,
也藉由這個程式,我們帶入一個讓程式與使用者互動的語法:cin。
範例 1. 3:
#include <stdlib.h>
#include <iostream>
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 _
cin >> rate; (22)read a decimal ralue from user thto rute _
cout << "Now you have $" << deposit*rate <<" NTD";
system("pause");
return 0;
範例 1. 3 輸出結果:
4
運算式的觀念
在變數的觀念裡,我們了解程式中資料存儲的方法;在範例 1. 3 裡,
我們利用兩個變數做乘法運算,以此為始,接下來我們要學習基本的
運算概念。
_ 时
運算式定義: (23) Epressnn: combonatonofoperands
a
operatong
$ _
運算子:(24) operater :
amonyoperands
an autioy (e g , t
. _ ,
-
, *)
, values varable
一些常用的基本運算子:
a. 指派運算子
(26) _
5
。
。
範例 1. 4: 交換兩個變數內的值 (Swap)
#include <stdlib.h>
#include <iostream>
int main( ) {
(29) X= Y ; _
(30) Y= temp ; _
system("pause");
Swap X sY wrthout any buffer
.
.
return 0;
Hint :
XOR
}
範例 1. 4 輸出結果:
x is 8 and y is 2
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
,
0
coutcc ( a > b )θ ( a! = b 1 )w
<c
州
! la > b ) | 1 ( a ! ;
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=
/=
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 女)
+ 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
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 了 .
Ciut ) f 3 ;
9
f2 =
型戀以最任yHhwt
int main( ) {
int a = 10;
float b = 4; 10 / 4 215 =
(f|oat) (x /y)
= 2
0 .5
“
6 83 (float) lX/y | /y
=
(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 _
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 ,
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
結束了嗎?其實還沒,若不考慮虛數,我們知道對負數開平方根是無效
的,我們加入一個簡單的條件式,告訴使用者,程式只能對大於等於
零的數開根號。這個簡單的條件式在程式設計裡也被稱為控制敘述
(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
17