【实用篇】13条 C/C++ 常用注意事项
C/C++ 是一门很值得学习的语言,但里面有不少易错的地方,可能会让大家困扰不少,下面让我们一起来看看这些要注意的地方吧。
1. 注意 int 有没有越界,又或者 long long 会不会 MLE。
2. 使用 float 时小数精度可能不够,而使用 double 依然要注意空间问题。
3. 提交自己的代码时,一定不要提交调试信息(如中途输出等),否则会 WA,这样有可能罚分或罚时。
4. 注意数组与变量的初始化!(大多数情况下,全局数组 int / long long / float / double 默认为0)
5. 注意千万不要将 == 写成 =,否则肯定会出问题。
6. n 和 m 要分清!
7. for 循环时,注意多层循环要有不同的变量循环(不能总是 i ,否则肯定要出事),搞清楚是 ++ 还是 --。
8. 逻辑判断时,注意 < 与 与 >=。
9. 如果觉得此段代码可能不再(或暂时)不需要了,应该将其注释,不应删除,以免后面可能再次使用。
10. 注意运算符优先序!
11. 看清楚题目要求的输出格式!(如 yes 与 Yes 与 YES 的区别)
12. 如果不知道那里有 bug,应分段调试,可以采用中间变量输出等方法。
13. 注意如果使用 scanf 输入,应加上 &,否则非法内存访问。
原文:
things to check1. int overflow or long long memory need2. recursion/array/binary search/dp/loop bounds3. precision4. special cases(n=1,bounds)5. delete debug statements6. initialize(especially multi-tests)7. = or == , n or m ,++ or -- , i or j , > or >= , < or <=8. keep it simple and stupid9. do not delete, use // instead10. operator priority11. is there anything extra to output?12. if you do not know where the bug is , try to clear some parts of the code and check each part seperately.something to think about1. greedy? dp? searching? dp with matrix/ segment tree? binary search?2. If contains "not", why not 正难则反 or few affect?