运算符(C++)

1、算术运算符

算数运算符包括+,-,*,/,%,递增,递减

代码解释:


#include <iostream>
using namespace std;
int main()
{
	int a = 10;
	int b = 5;          //cout<<a+b<<endl;  我这边加不加()都可以的,加了会增加可读性
	cout << (a + b) << endl;
	cout << (a - b) << endl;
	cout << (a * b) << endl;  
	cout << (a / b) << endl;
	cout << (a % b) << endl;

	float c = 2.1f;
	float d = 8.4f;    
	cout << (a / c) << endl;      //float有七位有效数字
	cout << (c / d) << endl;

	//cout << (a % c) << endl;    //报错 报错原因:右操作数类型为浮点型
	//cout << (d % c) << endl;    //报错 报错原因:左右操作数类型都为float
	
	//总结:取模运算符的左、右操作数必须为整数

	b = 0;
	//cout << (a / b) << endl;  //报错
	//cout << (a % b) << endl;    //报错 报错原因:取余数之前,需要进行除法运算
	
	//总结:除法运算中除数不能为0
	system("pause");
	return 0;
}

运行结果:
在这里插入图片描述
代码解释:

#include <iostream>
using namespace std;
int main()
{

	int a = 6;
	int b = 7;
	int c = 5;
	b = a++;  //后置++,b=6,a=7
	c = ++a;  //前置++,a=8,c=8

	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
	cout << "c=" << a << endl;

	system("pause");
	return 0;
	//总结:前置++,先++,再算表达式   ;后置++,先算表达式,再++
}

运行结果:
在这里插入图片描述

2、逻辑运算符

逻辑运算符有三种:!,&&,||

!表示非
&&表示与,只有操作数都为真,结果才为真,否则结果为0;
||表示或,左右操作数只要有一个为真,则为真,都为0,结果才为假;

代码解释:

#include <iostream>
using namespace std;
int main()
{
	int a = 0;
	int b = 4;
	cout << !a << endl;
	cout << (a && b ) << endl;
	cout <<( a || b )<< endl;

	system("pause");
	return 0;
}

运行结果:
在这里插入图片描述

3、比较运算符

比较运算符有>,<,==,>=,<=,!= 

代码解释:

#include <iostream>
using namespace std;
int main()
{
	int a = 9;
	int b = 4;
	//>
	cout << (a > b) << endl;
	//<
	cout << (a < b) << endl;
	//>=
	cout << (a >= b) << endl;
	//<=
	cout << (a <= b) << endl;
	//==
	cout << (a == b) << endl;
	//!=
	cout << (a != b) << endl;
	
	system("pause");
	return 0;
}

运行结果:
在这里插入图片描述

4、赋值运算符

赋值运算符就是 =

代码解释:

#include <iostream>
using namespace std;
int main()
{
	int a = 3;  //把3赋给a;
	float b = 9.98473165f;  //把9.98473165赋给b;
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
	system("pause");
	return 0;
}

运算结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值