Variables

by 芊竹

Variables in Math

Variables in Programming

  • 有不同的形態
  • 佔有記憶體
  • 值可以改
  • 唯一的值
x^2+2x+1=0
(x-1)^2+(y-1)^2=9

未知數

2x+3y+4Z=5
int a=5;
double b=3.14159;
long long int c=10000000000

Named Variables

A~Z

a~z

0~9

_

可以

不可以

在同個區域宣告相同名字的變數

數字開頭

用關鍵字命名

1a2b

num_max

int

X1

 

  • 小建議:為變數取有意義的名字

Variable Type

型態 中文 英文 儲存空間 數值範圍
int 整數 integer 4 bytes/ 32 bits -2^31~2^31-1 (10 位數)
long long 長整數 long long integer 8 bytes/ 64 bits -2^63~2^63-1 (19 位數)
float 浮點數 floating point 4 bytes/ 32 bits 3.4E +/- 38 (7 位數)
double 倍精度浮點數 double 8 bytes/ 64 bits 1.7E +/- 308 (15 位數)
char 字元 character 1 byte/ 8 bits 0~255(ASCII)
bool 布林 boolean 1 byte/ 8 bits false, true, 0~255

declare & assign

int x=10;
//宣告一個叫做x的整數型態變數,裡面放10
int y; //宣告
y=10; //賦值

x

10

這是一種int型號的箱子

cin & cout

double a; //宣告一個double型態的變數叫a
std::cin>>a; //輸入數值到a儲存
std::cout<<a; //輸出a的值

輸入:cin>>變數

輸出:cout<<變數

Other Examples

#include <iostream>
using namespace std;
int main(){
 	char a="A";
	cout<<a<<a;
	cout<<a<<" "<<a;
	cout<<a<<endl<<a;
    return 0;
}

Excercise 1

試試看下面的程式碼?

int num_1;
cin>>num_1;//記得輸入一個數字
num_1=5;
cout<<num_1;
int num_2,num_3=30;
cout<<num_2<<" "<<num_3;
num_2=num_3;
cout<<num_2<<" "<<num_3;
bool _b = false;  
//宣告名為_b的布林值,並賦值false
_b = true;  //將_b改為true
cout << "bool" << _b;  //輸出bool

Operators

Arithmetic Operator

+ 加,如 1+2

-  減,如 11-1→10

* 乘,如  10*10→100

/  整除,如9/2→4

% mod,如22%7→1

如何把變數的值加1

a=a+1

a+=1

a++

Exercise 2

▲電腦會先乘除後加減嗎?

▲負數mod(%)的結果是什麼?

▲int 可以和float運算嗎?

▲float的四則運算和int有什麼不一樣?

▲++a和a++有什麼不同?

Relational Operator

>大於

>=大於等於

<小於

<=小於等於

==等於

!=不等於

 

Logical Operators

!  not

&&  and 

||  or

ex.

1==2 || 1!=2 → true

2<3 && 3>4 → false

Truth Table

A B A||B
0 0 0
0 1 1
1 0 1
1 1 1
A !A
1 0
0 1
A B A&&B
0 0 0
0 1 0
1 0 0
1 1 1

Homework

Exercise 3

ans_Exercise 3

#include <iostream>
using namespace std;
int main(){
	int a,b;
    while(cin>>a>>b){
    cout<<a+b<<endl;
    }
    return 0;
}

Extending Readings

Array

只講小小觀念~

Variable

Array

變數

多個變數

declare

100

a

a[0]

a[1]

a[2]

a[4]

a[3]

a[5]

a[6]

a[7]

a[8]

a[9]

int a[10]; 
a[5]={100};

if

生活情境

如果有時間,就玩kahoot

code

if(條件1){
	如果條件1成立做的事
}
else if(條件2){
	如果條件1不成立、條件2成立,要做的事
}
else{
	條件1、條件2都不成立要做的事
}
if(score>=60){
	cout<<"pass"<<endl;
}
else{
	cout<<"fail"<<endl;
}

Exercise 4

Extending Readings

Homework

Nested If/Else

if (condition1) {
    if (condition1_1) {

    } else {

    }
} else if (condition2) {

} else {
    if (condition3_1) {
    }
}

Excercise 5

Homework

Made with Slides.com