02 - 第二章 开始学习C++
1. 进入C++
#include <iostream>
int main() {
/*
* 这是多行注释
* 这是多行注释
* 这是多行注释
*/
using namespace std;
cout << "Come up and C++ me some time."; // 这是单行注释
cout << endl;
cout << "You won't regret it!" << endl;
return 0;
}
2. C++语句
声明语句:创建变量。
赋值语句:给该变量提供一个值。
#include <iostream>
int main() {
using namespace std;
int carrots; // declare a variable
carrots = 10; // assign a value
cout << "I have ";
cout << carrots;
cout << " carrots." << endl;
carrots = carrots - 1; // modify the value of the variable
cout << "Crunch, Crunch. Now I have " << carrots << " carrots." << endl;
return 0;
}
3. 其它C++语句
cin : 读取键盘输入值。
#include <iostream>
int main() {
using namespace std;
int carrots; // declare a variable
cout << "How many carrots do you have?" << endl;
cin >> carrots;
cout << "Here are two more.";
carrots = carrots + 2;
cout << " Now you have " << carrots << " carrots." << endl;
return 0;
}
4. 函数
C++函数分两种:
-
有返回值的函数
-
没有返回值的函数
// 求平方根
x = sqrt(6.25)
代码示例:
#include <iostream>
#include <cmath>
int main() {
using namespace std;
double area;
cout << "Enter the floor area, in square feet, of your home: ";
cin >> area;
double side;
side = sqrt(area);
cout << "That's " << side << " feet to the side." << endl;
return 0;
}
5.用户定义函数
代码实例:用户定义无返回值函数
#include <iostream>
void simon(int); // function prototype for simon()
int main() {
using namespace std;
simon(3); // call the simon() function
cout << "Pick an integer: ";
int count;
cin >> count;
simon(count); // call it again
cout << "Done!" << endl;
return 0;
}
void simon(int n) {
using namespace std;
cout << "Simon says touch your toes " << n << " times." << endl;
}
代码实例:用户定义有返回值函数
#include <iostream>
int stonetolb(int); // function prototype
int main() {
using namespace std;
int stone;
cout << "Enter the weight in stone: ";
cin >> stone;
int pounds = stonetolb(stone);
cout << stone << " stone = " << pounds << " pounds." << endl;
return 0;
}
int stonetolb(int sts) {
return 14 * sts;
}
6. 总结
C++程序由一个或多个被称为函数的模块组成。程序从main( )函数 (全部小写)开始执行,因此该函数必不可少。函数由函数头和函数体组成。函数头指出函数的返回值(如果有的话)的类型和函数期望通过参数传递给它的信息的类型。函数体由一系列位于花括号({})中的 C++语句组成。
有多种类型的C++语句,包括下述6种。
-
声明语句:定义函数中使用的变量的名称和类型。
-
赋值语句:使用赋值运算符(=)给变量赋值。
-
消息语句:将消息发送给对象,激发某种行动。
-
函数调用:执行函数。被调用的函数执行完毕后,程序返回到函数 调用语句后面的语句。
-
函数原型:声明函数的返回类型、函数接受的参数数量和类型。
-
返回语句:将一个值从被调用的函数那里返回到调用函数中。
类是用户定义的数据类型规范,它详细描述了如何表示信息以及可对数据执行的操作。对象是根据类规范创建的实体,就像简单变量是根据数据类型描述创建的实体一样。 C++提供了两个用于处理输入和输出的预定义对象(cin和cout), 它们是istream和ostream类的实例,这两个类是在iostream文件中定义的。为ostream类定义的插入运算符(<<)使得将数据插入到输出流成为可能;为istream类定义的抽取运算符(>>)能够从输入流中抽取信息。cin和cout都是智能对象,能够根据程序上下文自动将信息从一种形式转换为另一种形式。
C++可以使用大量的C库函数。要使用库函数,应当包含提供该函数原型的头文件。
原文地址:https://blog.csdn.net/2301_76354366/article/details/142741698
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!