#include <iostream>
using namespace std;
int main()
{
int a = 1, b = 2;
int c;
c = a + b;
c = a - b;
c = a * b;
c = a / b; // 整数除法,自动向下取整
// %,模运算
c = a % b; // 9除2,商4,余1, 模运算,就是取余运算,c等于1
// 注意了
int a = -5;
cout << a % 2 << '\n'; // 输出 -1
int a = -5;
cout << a / 2 << '\n'; // 输出 -2,负数/2,向0取整
int a = -5;
cout << (a >> 1) << '\n'; // 输出 -3,负数右移一位,向负方向取整
return 0;
}
// 【扩展】
// 涉及负数的二进制表示,原码反码补码问题
// 教给大家一个自己玩的小东西,有了这个,就可以自己去验证原码反码补码的变化过程
// 进而,从根源上理解,而不是死记硬背
#include <bits/stdc++.h>
using namespace std;
void print(int x){
for (int j = 31; j >= 0; j--)
if (x >> j & 1) cout << 1;
else cout << 0;
puts("");
}
int main(){
int x = -5;
print(x);
x >>= 1;
print(x);
return 0;
}
// ++i, i++ 的区别
// ++i是,i先增加1位,赋值给别人
// i++是,i先赋值给别人,自己再增加1位
i++; // i从1变到了2
i--; // i从2变到了1
++i;
--i;
a += 2; a -= 2;
a += b; a -= b; // a = a + b;
int a = 2;
int b = a++;
//此时,b = 2, a = 3;
int a = 2;
int b = ++a;
//此时,b = 3, a = 3;
if (a == b){ //判断a和b相等
c = a + b;
}
if (a = b){
cout << '=' << '\n';
}
else{
cout << "!=" << '\n';
}
/*
测试数据
3 3
3 0
0 0
0 3
*/
// 一些大小关系的示例
if (a < b){...}
if (a <= b){...}
if (a != b){...}
if (a > b && a > c){...}
if (a > b || a > c){...}
if (!a){...} //对a取反,当a是0的时候,成立;当a非零的时候,不成立
//示例
int a = 0;
if (!a) cout << a << '\n';
// 运算的简写,包括 += -= *= /= %=
a += 5;
a -= 5;
// 前导零问题
cout << 00123 << '\n';
// 一些常用的数据函数
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int x = -2;
cout << abs(x) << '\n'; //绝对值,整数的取绝对值
double y = 1.2;
cout << floor(y) << '\n'; //向下取整
cout << ceil(y) << '\n'; //向上取整 (x + y - 1) / y
cout << fabs(y) << '\n'; //浮点数绝对值
cout << round(y) << '\n'; //四舍五入
double x = -3.2;
cout << round(x) << '\n';
int n = 16;
cout << sqrt(n) << '\n'; //开平方根,开根号 4*4=16 sqrt(16)=4
cout << pow(2, 3) << '\n'; //2^3=8
return 0;
}
例题,CSP2021-J1阅读程序第1题【拓展】
// 【拓展】
// 题目大意
// char table[0] = 0xff;
// cout << int(table[0]) << endl;
// 问,输出的是不是-1
#include <bits/stdc++.h>
using namespace std;
void print(int x){
for (int j = 31; j >= 0; j--)
if (x >> j & 1) cout << 1;
else cout << 0;
puts("");
}
int main(){
unsigned char x = 0xff;
char y = 0xff;
cout << (int)x << '\n';
print(x);
cout << (int)y << '\n';
print(y);
return 0;
}