蓝桥杯零基础到获奖-第4章 C++ 变量和常量
蓝桥杯零基础到获奖-第4章 C++ 变量和常量
文章目录
- 一、算术操作符
- 5.1 算术操作符
- 5.2 浮点数的除法
- 5.3 负数取模
- 5.4 数值溢出
- 5.5 练习
- 练习4:整数⼗位
- 练习5:时间转换
一、算术操作符
5.1 算术操作符
在写代码时候,⼀定会涉及到计算。为了⽅便运算,提供了⼀系列操作符,其中有⼀组操作符叫:算
术操作符。分别是: + - * / % ,这些操作符都是双⽬操作符。
注:操作符也被叫做:运算符,是不同的翻译,意思是⼀样的。
#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()
{int a = 10;int b = 0;int c = a / b;float d = 6.0;float e = d % 2;return 0;
}
5.2 浮点数的除法
#include <iostream>
using namespace std;
int main()
{float x = 6 / 4;cout << x << endl; // 1float y = 6.0 / 4; // 6/4.0结果是⼀样的cout << y << endl; // 1.5return 0;
}
上⾯⽰例中,尽管变量 x 的类型是 float (浮点数),但是 6 / 4 得到的结果是 1.0 ,⽽不是
1.5 。原因就在于 整数除法是整除,只会返回整数部分,丢弃⼩数部分。
如果希望得到浮点数的结果,两个运算数必须⾄少有⼀个浮点数,这时就会进⾏浮点数除法。
5.3 负数取模
• 负数也是⽀持取模的,但是负数求模结果的正负号由第⼀个运算数(操作数)的正负号决定。
#include <iostream>
using namespace std;
int main()
{cout << 11 % -5 << endl; // 1cout << -11 % -5 << endl; // -1cout << -11 % 5 << endl; // -1return 0;
}
5.4 数值溢出
前⾯我们了解到数据类型都有对应的数值范围,⽽在实际运算过程中可能会存在加法操作导致数据范围超过当前数据类型规定的范围,如下:
#include <iostream>
using namespace std;
int main()
{char a = 'Z';char b = a + 'Z';cout << b << endl; // 输出了不显⽰的内容//printf是格式化输出,后⾯章节会讲,这⾥暂不做讲解printf("%d", b); // -76,char的⼗进制内容return 0;
}
以 char 类型为例, char 的数值范围在 -128 ~ 127 ,当字符相加超过最⼤值后,打印出来的结果会变成负数,这与数据的存储有关
这里打印出来为什么是-76呢?
可以先看一下下面的图帮助理解

可以看到127+1就变成-128了这里就是一个环

那么就可以知道这个-76就是
Z的as码是90俩个就是90+90=180
180-127=53,那么127+1就是-128了,那么就是
180-127-1 = 52
-128 + 52 = -76 就是这么来的
5.5 练习
练习1:计算(a+b)*c
https://www.luogu.com.cn/problem/B2008
#include<bits/stdc++.h>
using namespace std;
int main()
{int a,b,c;cin>>a>>b>>c;cout<<(a+b)*c;return 0;}
练习2:带余除法
https://www.luogu.com.cn/problem/B2010
#include<bits/stdc++.h>
using namespace std;
int main()
{int a,b;cin>>a>>b;cout<<a/b<<" "<<a%b;return 0;
}
练习3:整数个位
https://ac.nowcoder.com/acm/problem/21990
#include<bits/stdc++.h>
using namespace std;
int main()
{int num;cin>>num;cout<<num % 10 ;}
练习4:整数⼗位
https://ac.nowcoder.com/acm/problem/21991
#include<bits/stdc++.h>
using namespace std;
int main()
{int num;cin>>num;cout<<num / 10 % 10;return 0;
}
练习5:时间转换
https://ac.nowcoder.com/acm/contest/18839/1031
#include<bits/stdc++.h>
using namespace std;
int main()
{int seconds;cin>> seconds;cout<< seconds / 60 / 60 << ' ' << seconds / 60 % 60 << ' ' << seconds % 60 ;}
