Transcript 投影片 1

C/C++ Basics (I)
Variables, Expressions and Assignments
Berlin Chen 2003
Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002
Introduction to C++
• Programming Languages
– Low-level languages
• Machine, assembly
– High-level languages
• B, C, C++, ADA, COBOL, FORTRAN
– Object-Oriented-Programming in C++
• C++ Terminology
– Programs and functions
– Basic Input/Output (I/O) with cin and cout
2
Introduction to C++
• C++ is thought of C with classes (and other
modern features added), is a high level language
• C is first developed by Dennis Ritchie of AT&T in the
1970s for the UNIX system
• Bjarne Stroustrup of AT&T developed C++ in the early
1980s
• Most C is a subset of C++, and so most C programs are
also C++ programs (The reverse is not true!)
3
C++ and Object-oriented Programming
(OOP)
• The main characteristics of OOP
– Encapsulation (資料封裝)
• A form of information hiding and abstraction
– Inheritance (繼承)
• Has to do with writing reusable code
– Polymorphism (多形)
• Refers to a way that a single name can have multiple
meanings in the context of inheritance
– OOP provides classes, a kind of data type combining
both data and algorithms(演算法)
– C++ tempers its OOP features
4
Outline
• Basic Characteristics
• Identifiers
– Keywords or Reserved Words
– Variables
• Data types
– Assigning Data for Variables
•
•
•
•
•
Literal Data or Constants
Console Input/Output
Escape Sequences
Arithmetic Operators
Type Casting
5
Basic Characteristics of C/C++
High level language
-readable
-machine independent
(portable)
…
void main(void)
{
cout << “Hello World ! \n”;
…
}
C/C++ Language
(Text Files)
xxx.cpp
Compiler 編譯器
VC++, gcc
Low level language
00100000
01101010
-unreadable
-machine dependent
…..
01101010
Machine Language
(Binary Files)
6
Basic Characteristics of C/C++
• C/C++ is case-sensitive (注意大小寫)
• A program composed of one to several
functions (函數)
– 每個C/C++都需有一個稱為main()的函數
函數名稱
int main(void)
{
statement_1;
statement_2;
函數定義
…
statement_n;
return 0; //結束函數
}
結束函數
函數標題
函數主體
敘述(statement)以
分號結束
註解(comment)以“//”為起
始
7
Basic Characteristics of C/C++
• Program Style - Readability
– 儘可能每行寫一個敘述(statement)
– 函數開始與結束之左右大括號各佔一行
– 函數主體之敘述從大括號處往內(右)縮
– 函數名稱與之後的左右括號不需要有空白
8
An example of C++ program
#include <iostream>
using namespace std;
void main (void)
{
const double RATE=6.9;
double deposit;
C++ 程式
標頭檔名及
名稱空間
cout << "Enter the amount of your deposit $";
cin >> deposit;
double newBalance;
newBalance= deposit+ deposit*(RATE/100.0);
cout << "In one year, the deposit will grow to\n"
<<"$"<< newBalance;
}
程式
執行
過程
Enter the amount of your deposit $ 100
In one year, the deposit will grow to
$106.9
輸入
9
Identifiers (識別字)
• Identifiers are items defined/used in a program
– Keywords (關鍵字)or Reserved Words (保留字)
– Variables (變數)、function names (函數名稱)、labels
(標記)
• Identifiers must start with either a letter (A-Z, az) or the under score symbol(_), and the
remaining characters must be letters (A-Z, a-z),
digits(0-9), or the underscore symbol(_)
• Identifiers are case sensitive and have no limit
to their length (大小寫有別、長度不受限)
10
Identifiers
• Valid (合法的) Identifiers: x, x1, x_1,
ABC123z7,…
• Invalid (不合法的) Identifiers: 12, 3x, %change,
data-1, myfirst.c
• Identifier started with underscore are informally
reserved for system (should avoid using it)
– 以底線為首的命名方式通常保留給系統使用,因此我們在變數、函
數等命名時儘量不要使用
• Identifier are usually spelled with their first letter
in lowercase
• topSpeed, bankRate1, bankRate2,
timeOfArrival, …
儘量使用有意義的名稱
11
Keywords or Reserved Words
• A special class of identifiers which have predefined
meaning in C/C++ and cannot be used as names
for variables or anything else
– 關鍵字或保留字是C/C++ Compiler本身所使用的
– 如: break
case
char
float
在某些編輯
do
goto
long
double 環境下保留字
會以特別的
if
else
..
…
….
顏色顯示
– 我們只能使用它們,不能重新定義它們
• Some predefined words, such as cin and cout are
not keywords, because they are not the core of
C/C++ language
12
Variables
• A memory location to store data for a program
• Must declare all data (variables) before use in
program
– Tell the compiler/computer what kind of data you will
be storing in variables
int numberOfBeans;
double oneWeight, totalWeight;
• Variables can be declared any place
– Declared either just before they are used or at the
start of a block “{” (or a function/procedure)
– 通常在程式或每個函式開頭宣告,也可以在程式任意
位置用到時才宣告
13
Variables
Memory
1000
numberOfBeans
599
1004
2108
oneWeight
399.14
2112
14
Variables
• Declaring (宣告) and Defining (定義)
– Declaring: the name of a variable is introduced
int numberOfBeans;
//整數宣告
char nKey;
//字元宣告
– Defining: the storage for the named variable is allocated
numberOfBeans=10000;
nKey=‘A’;
• A variable declaration both declares and
defines the variable
int numberOfBeans=10000;
char nKey=‘A’;
15
Basic Data Types
TYPE MEMORY SIZE RANGE
PRECISION
NAME USED
short 2 bytes
-32768 ~ +32767 整數
型態
浮點數
型態
字元或字串
型態
布林數
型態
int
4 bytes
float
4bytes
-2,147,483,648 ~ +2,147,483,647
±10-38 ~ ± 1038
7digits
double 8 bytes
± 10-308 ~ ± 10308 15digits
char
1byte
All ASCII
characters
-
bool
1 byte
true, false
-
有效位數及指數範圍不同
16
Assigning Data for Variables
• Initializing data in declaration statement
int myValue = 0; or int myValue(0);
• Assigning data during execution
myValue = 0;
– Lvalues (left-side) & Rvalues (right-side)
– Lvalues must be variables, Rvalues can be
any expression (運算式)
– Example:
distance = rate * time;
Lvalue: ‘distance’ , Rvalue: ‘rate * time’
17
Assigning Data for Variables
• Assigning data during execution (cont.)
VarName= Expression;
(變數=運算式;)
敘述(a statement)
– 將等號(=)右邊的運算式的值指定給左邊的變數
18
Assigning Data for Variables
• Compatibility of data assignments
– Type mismatches
– General Rule: Cannot place value of one
type into variable of another type
e.g.:
int intVar;
…
intVar = 2.99;
// 2 is assigned to intVar!
• Only integer part ‘fits’, so that’s all that goes
• Called ‘implicit’ or ‘automatic type conversion’
19
Assigning Data for Variables
• Example: char(字元) vs. short (整數)
#include <iostream>
using namespace std;
void main() //Relation Between char and short
{
char testChar='X';
short testShort=testChar;
cout << "The ASCII for "<<testChar<<" is "<<testShort<<"\n";
testChar=testChar+1;
testShort=testChar;
cout << "The ASCII for "<<testChar<<" is "<<testShort<<"\n";
testChar=122;
cout << "New testChar is "<<testChar<<"\n";
}
20
Assigning Data for Variables
• bool
– C++ assigns nonzero values to true and zero
value to false
bool start= true;
bool start= false;
bool start= 100 ; //start assigned true
bool start= 0 ; //start assigned false
int ans = true ; //start assigned 1
int ans = false; //start assigned 0
21
Literal Data or Constants (常數)
• Cannot change values during execution
Examples:
2
// Literal constant int 整數
575.34
// Literal constant double 浮點數
5.7534e2
// Literal constant double 浮點數
3.4e-2
// Literal constant double (0.034)
‘Z’
// Literal constant char 字元
“Hello World”
// Literal constant string 字串
• Called ‘literals’ (實字) because you ‘literally
typed’ them in your program!
22
Literal Data or Constants (常數)
• Naming of constants
– Literal constants provide little meaning
e.g.: seeing 24 in a program, tells nothing about
what it represents
– Use named constants instead
• Meaningful name to represent data
const double = 6.9;
– Called a ‘declared constant’ or ‘named
constant’
若程式中數個地方
用到同一個常數,
要修改其值,只要
修改符號定義一處
即可
• Now use it’s name wherever needed in program
– Added benefit: changes to value result in one fix
23
An example of C++ program
#include <iostream>
using namespace std;
void main (void)
{
constant double RATE=6.9;
double deposit;
C++ 程式
cout << "Enter the amount of your deposit $";
cin >> deposit;
double newBalance;
newBalance= deposit+ deposit*(RATE/100.0);
cout << "In one year, the deposit will grow to\n"
<<"$"<< newBalance;
}
程式
執行
過程
Enter the amount of your deposit $ 100
In one year, the deposit will grow to
$106.9
輸入
24
Escape Sequences
(逸出順序、控制碼)
• Backslash,(背斜線) \ preceding a character
(字元)
• Instructs compiler: a special ‘escape
character’ (逸出字元) is coming
– 逸出字元:字串及字元中無法顯示之字元
ESCAPE SEQUENCES
MEANING
\n
換行/新列 (New line)
\'
單引號 (single quote)
\"
雙引號 (double quote)
\a
響鈴 (bell)
25
Escape Sequences
#include <iostream>
using namespace std;
void main() //escape sequence
{
cout <<'\a'<<"This is a test for escape sequences\n";
cout <<"How about you \"computer course\"?\n";
}
26
Arithmetic Operators (算數運算子)
• 5 arithmetic operators
Arithmetic Operators
MEANING
+
*
相加
相減
相乘
/
相除
%
餘數(模數)
使用模數運算子時,必須兩個運算元都是整數才行
• Precedence (優先權) rules – standard rules
如 *,/,% 優先於 +,- ;由左至右之結合律 (associative)
float logs=120/4*5; //150 ? 6?
27
Arithmetic Operators (算數運算子)
#include <iostream>
using namespace std;
void main()
{
int numA, numB, finalResult;
cout << "請輸入第一個整數: "; cin >> numA;
cout << "請輸入第二個整數: "; cin >> numB;
finalResult=numA+numB;
cout << "相加的結果: " <<"$"<< finalResult<<"\n";
finalResult=numA-numB;
cout << "相減的結果: " <<"$"<< finalResult<<"\n";
finalResult=numA*numB;
cout <<"相乘的結果: " <<"$"<< finalResult<<"\n";
finalResult=numA/numB;
cout <<"相除的結果: " <<"$"<< finalResult<<"\n";
finalResult=numA%numB;
cout <<"相除的餘數: " <<"$"<< finalResult<<"\n";
}
28
Arithmetic Precision
(算數運算精確度)
• ‘Highest-order operand’ determines type
of arithmetic ‘precision’ performed
– Common pitfall!
• Examples:
– 17 / 5 evaluates to 3 in C++! (Both operands are integers)
• Integer division is performed!
– 17.0 / 5 equals 3.4 in C++!
• Highest-order operand is ‘double type’
• Double ‘precision’ division is performed!
– int intVar1 =1, intVar2=2;
intVar1 / intVar2 equals 0 in C++!
• Performs integer division!
29
Arithmetic Precision
• Calculations done ‘one-by-one’
– 1 / 2 / 4.0 / 8 performs 3 separate divisions
• First 1 / 2 equals 0
• Then 0 / 4.0 equals 0.0
• Then 0.0 / 8 equals 0.0!
– What if 1 / 4.0/ 2 / 8 ?
30
Type Casting (型態轉換 )
• Implicit – also called ‘Automatic’
– Done for you by C++ automatically
17 / 5.5
‘implicit type cast’ to take place,
casting the 17 17.0
• Explicit type conversion
– Programmer specifies conversion with cast operator
(double)17 / 5.5; or double(17 )/ 5.5;
old C syntax
old C++ syntax
(double) myInt / myDouble;
31
Shorthand Operators
• Increment (++)& Decrement (--) Operators
– Just short-hand notation
• Increment operator,++
intVar++; is equivalent to
intVar = intVar + 1;
• Decrement operator, -intVar--; is equivalent to
intVar = intVar – 1;
32
Shorthand Operators
Post-Increment in Action
• Post-Increment in Expressions:
int n = 2, valueProduced;
valueProduced = 2 * (n++);
cout << valueProduced << "\n";
cout << n << "\n";
– This code segment produces the output:
4
3
– Since post-increment was used
33
Shorthand Operators
Pre-Increment in Action
• Now using Pre-increment:
int n = 2, valueProduced;
valueProduced = 2 * (++n);
cout << valueProduced << "\n";
cout << n << "\n";
– This code segment produces the output:
6
3
– Because pre-increment was used
34
Console Input/Output
• I/O objects: cin, cout
• Defined in the C++ library called
<iostream>
– Must have these lines (called pre-processor
directives) near start of file
#include <iostream>
using namespace std;
– Tells C++ to use appropriate library so we can
use the I/O objects cin, cout
35
Console Input/Output
• Console Output
– What can be outputted?
– Any data can be outputted to display screen
• Variables
• Constants or Literals
• Expressions (which can include all of above)
– cout << numberOfGames << " games played.";
(2 values are outputted: ‘value’ of variable
numberOfGames, literal string “ games played.”)
• Cascading: multiple values in one cout
36
Console Input/Output
• Formatting Output
– Formatting numeric values for output
– Values may not display as you’d expect!
cout << " The price is $ " << price << "\n";
– If price (declared double) has value 78.5, you
might get:
• The price is $78.500000
• The price is $78.5
or:
– We must explicitly tell C++ how to output
numbers in our programs!
37
Console Input/Output
• Formatting Output
– ‘Magic Formula’ to force decimal sizes:
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
– These statements force all future continued
values:
• To have exactly two digits after the decimal place
– Example:
cout << “The price is $” << price << endl;
– Now results in the following:
The price is $78.50
38
Console Input/Output
• Input Using cin
– ‘>>’ (extraction operator) points opposite
– No literals allowed for cin. Must input ‘to a
variable’
cin >> num;
– Waits on-screen for keyboard entry
– Value entered at keyboard is ‘assigned’ to
num
39
Program Style
• Bottom-line (底線): Make programs easy
to read and modify
• Comments, two methods:
– // Two slashes indicate entire line is to be ignored
– /*Delimiters indicates everything between is ignored*/
• Identifier naming
– ALL_CAPS for constants
– lowerToUpper for variables
– Most important: MEANINGFUL NAMES!
40
Libraries
• C++ Standard Libraries
#include <Library_Name> (標頭檔)
– Directive to ‘add’ contents of library file to
your program
– #include is called ‘preprocessor directive’ (前
端處理程式指令)
– Executes before compiler, and simply ‘copies’
library file into your program file
• C++ has many libraries
– Input/output, math, strings, etc.
41
Namespaces (名稱空間)
• Namespaces defined:
– Collection of name definitions
• Examples:
– Includes entire standard library of name
definitions
#include <iostream>
using namespace std;
– Can specify just the objects we want
#include <iostream>
using std::cin;
using std::cout;
42
Summary 1
• C++ is case-sensitive
• Use meaningful names
– For variables and constants
• Variables must be declared before use
– Should also be initialized
• Use care in numeric manipulation
– Precision, parentheses, order of operations
• #include C++ libraries as needed
43
Summary 2
• Object cout
– Used for console output
• Object cin
– Used for console input
• Use comments to aid understanding of
your program
– Do not overcomment
44
ASCII 碼
45
擴充字元集 (Extended Character Set)
46
如何使用 MS Visual C++ 6.0 之
整合程式設計環境 (IDE)
• 打開 Microsoft Visual C++ 6.0
打開MS Visual C++ 6.0
47
如何使用 MS Visual C++ 6.0 之
整合程式設計環境 (IDE)
• 產生一個 Console mode project (專案)-1
1
選擇 下拉視窗 File 下的 New 選項
48
如何使用 MS Visual C++ 6.0 之
整合程式設計環境 (IDE)
• 產生一個 Console mode project - 2
輸入 project 的名稱
3
2
選擇 Console 模式的 project
49
如何使用 MS Visual C++ 6.0 之
整合程式設計環境 (IDE)
• 產生一個 Console mode project -3
4
50
如何使用 MS Visual C++ 6.0 之
整合程式設計環境 (IDE)
• 產生一個 Console mode project -4
5
新增檔案到 Project
51
如何使用 MS Visual C++ 6.0 之
整合程式設計環境 (IDE)
• 產生一個 Console mode project -5
6
7
選擇新增檔案的類型
為.cpp 即 C++ 程式
輸入新增檔案為.cpp
即 C++ 程式
52
如何使用 MS Visual C++ 6.0 之
整合程式設計環境 (IDE)
• 產生一個 Console mode project -5
10
9
按兩下即可在
右邊視窗編輯
編輯你的程式
選擇程式視窗
8
53
如何使用 MS Visual C++ 6.0 之
整合程式設計環境 (IDE)
• 產生一個 Console mode project -6
11
編輯你的程式
54
如何使用 MS Visual C++ 6.0 之
整合程式設計環境 (IDE)
• 產生一個 Console mode project -7
12
產生程式的執行檔
55
如何使用 MS Visual C++ 6.0 之
整合程式設計環境 (IDE)
• 產生一個 Console mode project -8
13
Compile 的結果
56
如何使用 MS Visual C++ 6.0 之
整合程式設計環境 (IDE)
• 產生一個 Console mode project -9
14
執行程式
57
如何使用 MS Visual C++ 6.0 之
整合程式設計環境 (IDE)
• 產生一個 Console mode project -10
15
執行程式
58