算术操作符
算术操作符
在写代码时候,⼀定会涉及到计算。为了⽅便运算,提供了⼀系列操作符,其中有⼀组操作符叫:算术操作符。分别是: + - * / % ,这些操作符都是双⽬操作符。有两个操作数。
操作符也被叫做:运算符。
#include <iostream>
using namespace std;
int main()
{
int a = 7 + 2; // 加法运算
int b = 7 - 2; // 减法运算
int c = 7 * 2; // 乘法运算
int d = 7 / 2; // 除法运算得到的是整除后的商
int e = 7 % 2; // 取余运算,得到的是整除后的余数
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << d << endl;
cout << e << endl;
return 0;
}
- / 除法的操作符,除数不能为0,如果除数为0,程序会崩溃的。
- % 取模操作符的计算结果是两个操作数进⾏除法运算后的余数。
- 取模操作符的操作数只能是整型,不能是浮点型,这个编译器会报语法错误的。
浮点数的除法
#include <iostream>
using namespace std;
int main()
{
float x = 6 / 4;
cout << x << endl; // 1
float y = 6.0 / 4; // 6/4.0结果是⼀样的
cout << y << endl; // 1.5
return 0;
}
上⾯⽰例中,尽管变量 x 的类型是 float (浮点数),但是 6 / 4 得到的结果是 1.0 ,⽽不是1.5 。原因就在于整数除法是整除,只会返回整数部分,丢弃⼩数部分。
如果希望得到浮点数的结果,两个运算数必须⾄少有⼀个浮点数,这时就会进⾏浮点数除法。
负数取模
负数也是⽀持取模的,但是负数求模结果的正负号由第⼀个运算数(操作数)的正负号决定。
#include <iostream>
using namespace std;
int main()
{
cout << 11 % -5 << endl; // 1
cout << -11 % -5 << endl; // -1
cout << -11 % 5 << endl; // -1
return 0;
}
数值溢出
数据类型都有对应的数值范围,⽽在实际运算过程中可能会存在加法操作导致数据范围超过当前数据类型规定的范围
#include <iostream>
using namespace std;
int main()
{
char a = 'Z'; //90
char b = a + 'Z'; //180
cout << b << endl; // 输出了不显⽰的内容
printf("%d", b); // -76,char的⼗进制内容
return 0;
}
以 char 类型为例, char 的数值范围在 -128 ~ 127 ,当字符相加超过最⼤值后,打印出来的结
果会变成负数,这与数据的存储有关
练习
B2008 计算 (a+b)×c 的值 - 洛谷
#include <iostream>
using namespace std;
int main()
{
int a, b, c;
cin >> a >> b >> c;
cout << (a + b) * c << endl;
return 0;
}
这个题⽬⼀定能注意,数据范围, − 1 0 4 < a , b , c < 1 0 4 -10^4<a,b,c<10^4 −104<a,b,c<104 ,(a+b)*c
的结果也不会超过有符号整型的最⼤值,⽽如果取值范围变成 − 1 0 5 < a , b , c < 1 0 5 -10^5<a,b,c<10^5 −105<a,b,c<105,就需要使⽤ long long 类型了。
B2010 带余除法 - 洛谷
#include <iostream>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
cout << a / b << " " << a % b << endl;
return 0;
}
整数个位
#include <iostream>
using namespace std;
int main()
{
int a;
cin >> a;
cout << a % 10 << endl;
return 0;
}
整数十位
#include <iostream>
using namespace std;
int main()
{
int a;
cin >> a;
cout << a / 10 % 10 << endl;
return 0;
}
时间转换
#include <iostream>
using namespace std;
int main()
{
int S, h, m, s;
cin >> S;
h = S / 3600;
m = S % 3600 / 60;
s = S % 3600 % 60;
cout << h << ' ' << m << ' ' << s << endl;
return 0;
}
int 的数量级是 1 0 9 10^9 109
#include <iostream>
using namespace std;
int sec;
int main()
{
cin >> sec;
int h = sec / 60 / 60;
int m = sec / 60 % 60;
int s = sec % 60;
cout << h << ' ' << m << ' ' << s << endl;
return 0;
}
- time除以60(1分钟有60秒)先换算出分钟数,分钟数除以60(1⼩时有60分钟)交换算
成⼩时。 - time除以60(1分钟有60秒)先换算出分钟数,分钟数对60取模,就是换完⼩时后剩余的
分钟数 - time对60取模,每60秒凑1分钟,还剩多少多少秒,没办法凑够⼀分钟。
P1425 小鱼的游泳时间 - 洛谷
#include <iostream>
using namespace std;
int a, b, c, d;
int main()
{
cin >> a >> b >> c >> d;
int t1 = a * 60 + b;
int t2 = c * 60 + d;
int t = t2 - t1;
int e = t / 60; // 小时
int f = t % 60; // 分钟
cout << e << " " << f << endl;
return 0;
}