00-认识C++

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

函数的定义在文件中依次出现,如下图所示

请添加图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值