CPP从头学起3:运算符

运算符:

作用:执行代码运算等操作。

运算符的类型:

1. 算数运算符:

三个大类:加减乘除,取模运算,前置后置。

(1)加减乘除:

如下:

#include <iostream>
using namespace std;
#include <string>//CPP风格字符串要包含这个头文件
int main() 
{
	int a = 10;
	int b = 3;
	cout << a+b << endl;
	cout << a / b << endl;
	system("pause");
	return 0;
}

注意:根据结果发现,a/b 的结果为3,而不是3.333。这是因为对于a和b的定义都是Int,即整型整数,所以相除结果也是整数,小数部分去除掉。

对应的,小数相除使用double就可以了,如下。

#include <iostream>
using namespace std;
#include <string>//CPP风格字符串要包含这个头文件
int main() 
{
	double a = 0.23;
	double b = 0.12;
	cout << a+b << endl;
	cout << a / b << endl;
	system("pause");
	return 0;
}

结果如下所示。

(2)取模运算:

本质就是:求余数。(取模运算只基于整数 Int )

代码验证:

#include <iostream>
using namespace std;
#include <string>//CPP风格字符串要包含这个头文件
int main() 
{
	int  a = 10;
	int b = 3;

	cout << a % b << endl;
	system("pause");
	return 0;
}

结果如下。

(3)前置后置:

a. 前置递增:
#include <iostream>
using namespace std;
#include <string>//CPP风格字符串要包含这个头文件
int main() 
{
	int  a = 10;
	++a; //让变量加1

	cout << a << endl;
	system("pause");
	return 0;
}

输出结果:

b. 后置递增:
#include <iostream>
using namespace std;
#include <string>//CPP风格字符串要包含这个头文件
int main() 
{
	int  a = 10;
	a++; //让变量加1

	cout << a << endl;
	system("pause");
	return 0;
}

输出结果也是11。

c. 前置和后置递增的区别:

前置:++a 先变量加1,再进行表达式运算。

后置:a++ 先进行表达式运算,再变量加1 。

如下对比:

前置:

#include <iostream>
using namespace std;
#include <string>//CPP风格字符串要包含这个头文件
int main() 
{
	int  a = 10;
	int  b = ++a*10;
	
	cout << a << endl;
	cout << b << endl;
	system("pause");
	return 0;
}

对应结果为:

后置:

#include <iostream>
using namespace std;
#include <string>//CPP风格字符串要包含这个头文件
int main() 
{
	int  a = 10;
	int  b = a++*10;
	
	cout << a << endl;
	cout << b << endl;
	system("pause");
	return 0;
}

对应结果为:

2. 赋值运算符:

作用:变量赋值。

比如:a += 2 对应就是a = a + 2 。

3. 比较运算符:

作用:用于表达式的比较,并返回一个真 1 或者假值 0 。

4. 逻辑运算符:

作用:根据表达式的值,返回真 1 或者假 0 。

#include <iostream>
using namespace std;
#include <string>//CPP风格字符串要包含这个头文件
int main() 
{
	int  a = 10;

	cout <<! a << endl;

	system("pause");
	return 0;
}

结果如下:

注意:在CPP中,除了0都是真,但习惯用1来代表真。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值