C++ 簡介/語句製作
C++ 的 if 關鍵字執行基本的條件測試。如果條件為 true,則執行操作。它的語法如下所示
if(test-expression){statements-to-perform-when-true}
如果關係為 false,我們可能需要執行不同的操作。透過新增 else 語句,這是可能的。if-else 語句如下所示
if(test-expression){statements-to-perform-when-true} else{statements-to-perform-when-true}
#include <iostream>;
using namespace std;
int main{
int i=18;
if(i>17){
cout << "It's nice temperature." << endl;
return 0;
}
#include <iostream>;
using namespace std;
int main{
int i=4;
if(i<15){ cout << "Too cold, turn on the heater."<< endl;}
else if(15<=i<25){ cout << "It's nice temperature."<< endl;}
else{ cout << "Too hot! Please turn on the air conditioner" << endl;}
return 0;
}
當我們需要檢查多個情況時,重複使用 if-else 語句效率不高。在這種情況下,switch 更有用。switch 的工作方式不同。括號中的給定變數值嘗試在花括號中的多個 case 值中找到匹配值,並根據 case 值執行語句。每個語句以分號結尾。花括號中的每個值以 break; 結尾。break; 允許 switch 塊在語句執行後停止,並且 switch 塊滿足了程式。switch 語法如下所示
switch(variable-value){
case value1: statements-to-be-executed;break;
case value2: statements-to-be-executed;break;
...................
case valuen: statements-to-be-executed;break;
default:statements-to-be-executed; }
#include <iostream>
using namespace std;
int main(){
int season=2
switch( season )
{
case 1: cout << season <<":spring with sprout ";break;
case 2: cout << season <<":cool summer with ice tea";break;
case 3: cout << season <<"colorful autumn with fallen leaves:";break;
case 4: cout << season <<":snowy winter and hot chocolate";break;
}
return 0;
}
迴圈 是程式中自動重複的一段程式碼。C++ 程式設計中的三種迴圈是 for 迴圈、while 迴圈和 do while 迴圈。語法如下表所示
| for 迴圈 | for(initializer; test-expression;incrementer){statements-to-be executed} |
|---|---|
| while 迴圈 | while(test-expression){statements-to-be executed} |
| Do while 迴圈 | do{statements-to-be executed}while(test-expression) |
#include <iostream>
using namespace std;
int main(){
cout<<"Fibonacci sequence by For loop"<< endl;
int i,j=0;
for(i=0;i<10;++i){
cout << j+=i << endl;
return 0;
}
#include <iostream>
using namespace std;
int main(){
cout<<"Fibonacci sequence by while loop"<< endl;
int i=0,j=0;
while(i<10){cout << j+=i << endl;++i;}
return 0;
}
#include <iostream>
using namespace std;
int main(){
cout<<"Fibonacci sequence by do while loop"<< endl;
int i=0,j=0;
do{cout << j+=i << endl;++i;} while(i<10)
return 0;
}
#include <iostream>
using namespace std;
int main(){
return 0;
}
在 C++ 中,函式是提供程式某些功能的一組程式碼。當從主程式呼叫函式時,函式中的語句將被執行。函式使程式程式碼更易於理解,並有助於多個程式設計師協同工作。測試過的函式可以重複使用。每個函式都需要在程式開始時宣告。函式原型宣告的語法如下所示
return-data-type function-name(arguments-data-type list)
函式可以在宣告函式之後,在 main 函式之外定義。函式的語法如下所示
return-data-type function-name(arguments-data-type list){statements-to-be-executed}
#include <iostream>
using namespace std;
float trianglearea(float, float);
int main(){
float x,y,z;
cout << "Enter the width of triangle area:"<< endl;
cin >> x;
cout <<endl<<"Enter the height of triangle area:"<< endl;
cin >> y;
z=trianglearea(x,y);
cout <<endl<<"The dimension of triangle area:"<< z <<"sq.ft"<< endl;
return 0;
}
float trianglearea(float width, float height){
return ((width/2)*height);
}