2、认识C++
2.1、例子
一个简单的C++例子
#include <iostream>
int main() {
using namespace std; //使用名称空间
cout << "Com up and C++ me some time.";
cout << endl; //换行符,还可以cout<<"\n";
cout << "You won't regret it!" << endl;
std::cout << "You won't regret it!" << endl;
return 0;
}
对于头文件的命名约束
2.2、变量
#include <iostream>
int main() {
using namespace std;
int carrots; //定义或声明变量
carrots = 25;
cout << "I have ";
cout << carrots;
cout << " carrots. " << endl;
carrots = carrots - 1;
cout << "Now I have " << carrots << " carrots." << endl;
return 0;
}
cout和printf()
cout能够识别类型的功能说明,其设计更灵活、好用。另外,它时可扩展的,也就是说,可以重新定义<<运算符,使cout能够识别和显示所开发的新数据类型。
而对于printf(),需要使用%d、%s等格式化控制符
2.3、其他C++语句
使用cin
#include <iostream>
int main() {
using namespace std;
int carrots;
cout << "How many carrots do you have?" << endl;
cin >> carrots; //input
cout << "Here are two more.";
carrots = carrots + 2;
cout << "Now you have " << carrots << " carrots." << endl; //使用<<将多个输出语句拼接
return 0;
}
2.4、函数
对于函数
#include <iostream>
#include <cmath>
int main() {
using namespace std;
double area;
cout << "Enter the floor area." << endl;
cin >> area;
double size;
size = sqrt(area);
cout << "That's the equivalent of a square " << size << " feet to the side." << endl;
return 0;
}
对于函数的调用,有下面的图展示
也可以自己定义函数
#include <iostream>
void simon(int); //函数的声明
int main() {
using namespace std;
simon(3);
cout << "Pick an integer:";
int count;
cin >> count;
simon(count);
return 0;
}
//函数的定义
void simon(int n) {
using namespace std;
cout << "Simon says touch your toes " << n << " times." << endl;
}
函数的定义在文件中依次出现,如下图所示