tags: tgirc早修book

四則運算

常用運算符號

  • 加法:x + y
  • 減法:x - y
  • 乘法:x * y
  • 除法:x / y (小數點無條件捨去)
  • 取餘數(mod):x % y (5%3 == 2)

其他運算函式

可引入數學函式庫,使用更多的功能
#include <cmath>

x的y次方:pow(x, y)
根號x:sqrt(x)

範例 1
計算 x2+1

#include <iostream> #include <cmath> using namespace std; int main(){ int x; //宣告整數變數x cin>>x; //將輸入內容存入x cout<<pow(x,2)+1<<"\n"; //輸出x的平方 ( pow(x,2) ) 加一之後,再輸出一個換行 ("\n") return 0; }

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

在程式中,和平常進行運算時一樣,都是先乘除後加減,想先計算加減時,可用 () 包起來,最內層的 () 會先進行運算

範例 2

#include <iostream> using namespace std; int main(){ cout<<(6+(7+8*(9-4)))*2<<"\n"; //先執行最內層括號內的9-4等於5 //然後5再先乘除後加減,將5*8等於40 //40+7等於47 //至此,將47加上6等於53,最後再乘上最外層的2=106 return 0; }

賦值

除了使用 cin 給予變數一個值以外,可以使用 = 直接賦予變數一個初始值

#include <iostream> using namespace std; int main(){ int num,num2=2,num3; //宣告num與num3,不賦予初始值 //宣告num2,並賦予初始值為2 //此時num2的值為2 num3=3; //將3賦予num3,此時num3的值為3 cin>>num; //將輸入值賦予給num cout<<num<<" + "<<num2<<" + "<<num3<<" = "; //用雙引號「"」框起來的為字串,沒框起來的是變數依各符號功能做處理 //依序輸出 num、「+」符號、num2、「+」符號、num3 cout<<num+num2+num3<<"\n"; //輸出 num+num2+num3 的「值」 return 0; }

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

也可讓一個變數的值 = 另一個變數的值(將一個變數的值賦予給另一個變數),甚至做運算

#include <iostream> using namespace std; int main(){ int num=3,num2,num3; //宣告num,並賦予初始值3 num2=num; //將num的值3賦予num2,此時num2的值為3 num3=num+num2*2; //將num+num2*2,也就是等於3(num的值)+3(num2的值)*2 //所以3+3*2=3+6=9,將9賦予num3 //此時num3的值為9 cout<<"num: "<<num<<"\nnum2: "<<num2<<"\nnum3: "<<num3<<"\n"; //「\n」表示換行 return 0; }

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

表示 num = num + 3; 時,可寫為 num += 3; ,其他 -*/% 也都可使用這種方法進行操作。

num++;num += 1; 意義相同,num--; 也與 num -= 1; 相同