1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. int a = 1, b = 2;
  6. int c;
  7. c = a + b;
  8. c = a - b;
  9. c = a * b;
  10. c = a / b; // 整数除法,自动向下取整
  11. // %,模运算
  12. c = a % b; // 9除2,商4,余1, 模运算,就是取余运算,c等于1
  13. // 注意了
  14. int a = -5;
  15. cout << a % 2 << '\n'; // 输出 -1
  16. int a = -5;
  17. cout << a / 2 << '\n'; // 输出 -2,负数/2,向0取整
  18. int a = -5;
  19. cout << (a >> 1) << '\n'; // 输出 -3,负数右移一位,向负方向取整
  20. return 0;
  21. }
  1. // 【扩展】
  2. // 涉及负数的二进制表示,原码反码补码问题
  3. // 教给大家一个自己玩的小东西,有了这个,就可以自己去验证原码反码补码的变化过程
  4. // 进而,从根源上理解,而不是死记硬背
  5. #include <bits/stdc++.h>
  6. using namespace std;
  7. void print(int x){
  8. for (int j = 31; j >= 0; j--)
  9. if (x >> j & 1) cout << 1;
  10. else cout << 0;
  11. puts("");
  12. }
  13. int main(){
  14. int x = -5;
  15. print(x);
  16. x >>= 1;
  17. print(x);
  18. return 0;
  19. }
  1. // ++i, i++ 的区别
  2. // ++i是,i先增加1位,赋值给别人
  3. // i++是,i先赋值给别人,自己再增加1位
  4. i++; // i从1变到了2
  5. i--; // i从2变到了1
  6. ++i;
  7. --i;
  8. a += 2; a -= 2;
  9. a += b; a -= b; // a = a + b;
  10. int a = 2;
  11. int b = a++;
  12. //此时,b = 2, a = 3;
  13. int a = 2;
  14. int b = ++a;
  15. //此时,b = 3, a = 3;
  16. if (a == b){ //判断a和b相等
  17. c = a + b;
  18. }
  19. if (a = b){
  20. cout << '=' << '\n';
  21. }
  22. else{
  23. cout << "!=" << '\n';
  24. }
  25. /*
  26. 测试数据
  27. 3 3
  28. 3 0
  29. 0 0
  30. 0 3
  31. */
  32. // 一些大小关系的示例
  33. if (a < b){...}
  34. if (a <= b){...}
  35. if (a != b){...}
  36. if (a > b && a > c){...}
  37. if (a > b || a > c){...}
  38. if (!a){...} //对a取反,当a是0的时候,成立;当a非零的时候,不成立
  39. //示例
  40. int a = 0;
  41. if (!a) cout << a << '\n';
  42. // 运算的简写,包括 += -= *= /= %=
  43. a += 5;
  44. a -= 5;
  45. // 前导零问题
  46. cout << 00123 << '\n';
  1. // 一些常用的数据函数
  2. #include <iostream>
  3. #include <cmath>
  4. using namespace std;
  5. int main()
  6. {
  7. int x = -2;
  8. cout << abs(x) << '\n'; //绝对值,整数的取绝对值
  9. double y = 1.2;
  10. cout << floor(y) << '\n'; //向下取整
  11. cout << ceil(y) << '\n'; //向上取整 (x + y - 1) / y
  12. cout << fabs(y) << '\n'; //浮点数绝对值
  13. cout << round(y) << '\n'; //四舍五入
  14. double x = -3.2;
  15. cout << round(x) << '\n';
  16. int n = 16;
  17. cout << sqrt(n) << '\n'; //开平方根,开根号 4*4=16 sqrt(16)=4
  18. cout << pow(2, 3) << '\n'; //2^3=8
  19. return 0;
  20. }

例题,CSP2021-J1阅读程序第1题【拓展】

  1. // 【拓展】
  2. // 题目大意
  3. // char table[0] = 0xff;
  4. // cout << int(table[0]) << endl;
  5. // 问,输出的是不是-1
  6. #include <bits/stdc++.h>
  7. using namespace std;
  8. void print(int x){
  9. for (int j = 31; j >= 0; j--)
  10. if (x >> j & 1) cout << 1;
  11. else cout << 0;
  12. puts("");
  13. }
  14. int main(){
  15. unsigned char x = 0xff;
  16. char y = 0xff;
  17. cout << (int)x << '\n';
  18. print(x);
  19. cout << (int)y << '\n';
  20. print(y);
  21. return 0;
  22. }