# 運算子與數學函式 算數運算子,邏輯運算子幾乎與 python , java一樣,在此不做贅述 針對比較特殊的位元運算子做講解 and寫成`&&` , or 寫成`||` , not寫成 `!` # 算數運算子 補充一個,再C++中 `cout << (2%2==0)` 會輸出1 :::warning C++ 的除法 `/` 是採用向下取整(結果為正)跟向上取整 ::: # 位元運算子 很酷的一個東西 會把大家都變成二進位來判斷 - `&` 大家都1才ok - `|` 有一個1就行了 - `^` 互斥,兩個都不一樣才1 ```cpp inti=5 &3; // =1 int i = 5 | 3; // =7 int i = 5 ^ 3; // =6 ``` 計算過程: ![image](https://hackmd.io/_uploads/HyWbTZzFyl.png) ## 位移運算子 > bitwise shift operator 把數字的二進位往左或往右移。 ```cpp= int x = 3; // 二進位: 000...0011 int y = x << 2; // 左移兩位: 000...1100 = 12 int z = x >> 1; // 右移一位: 000...0001 = 1 ``` 後面章節會再做詳細說明。 # 數學函式 * **sqrt(a)** : 計算a的平方根 * **pow(a,b)**: 計算a^b :::danger 注意pow、sqrt是回傳double的型別,如果用int去接,在數字大時容易造成溢位出線的精度不准。 **這時會建議用位移運算子** ::: --- `#include <algorithm>` or `#include <bits/stdc++.h>` ### 轉換 ```cpp= int main() { int num = 123; string str = to_string(num); cout << "The integer is: " << num << endl; cout << "The string is: " << str << endl; return 0; } ``` ### 比大小 max() , min() ```c= #include <algorithm> using namespace std; int main(){ int j,k; cin >> j >> k; cout << min(j,k); return 0; } ``` ### 絕對值 abs() ```c= #include <iostream> #include <cmath> using namespace std; int main(){ int a; cin >> a; cout << abs(a) <<'\n'; return 0; } ``` ### 最大公因數 __gcd() ```c= #include <iostream> #include <algorithm> using namespace std; int main(){ int a,b; cin >> a >> b; cout << __gcd(a,b) <<'\n'; return 0; } ``` # 算數運算子 - 練習 不能用if,你能完成嗎 :::info d060 給你現在的分鐘數 輸出距離25分下課還有多久 ::: ```cpp= int n; cin >> n; cout << (85-n)%60; ``` :::info d485: 我愛偶數 輸出範圍a~b中的偶數數量 ::: ```cpp= int n,m; cin >> n >> m; cout << (m-n)/2 + (n%2==0 || m%2==0); } ```