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);
}