1. 運算結果超出類型大小:
#include <stdio.h>#include <limits.h>int main(void){ short s1 = SHRT_MAX; short s2 = SHRT_MAX; short num1; int num2; /* 不會是期望的值 */ num1 = s1 + s2; printf("%d\n", num1); /* 這樣可以了 */ num2 = s1 + s2; printf("%d\n", num2); getchar(); return 0;}
2. 把大的賦給小的:
#include <stdio.h>#include <limits.h>int main(void){ unsigned int n1 = INT_MAX; unsigned char n2; unsigned short n3; n2 = n1; n3 = n1; printf("%u, %u, %u\n", n1, n2, n3); printf("%#X, %#X, %#X\n\n", n1, n2, n3); n1 = LLONG_MAX; printf("%lld, %u\n", LLONG_MAX, n1); printf("%#llx, %#x\n", LLONG_MAX, n1); getchar(); return 0;}
3. 把浮點數賦給整數:
#include <stdio.h>int main(void){ double pi = 3.14159265; int i; /* 只會留下整數部分 */ i = pi; printf("%d\n", i); /* 並且不會四捨五入 */ i = 3.6; printf("%d\n", i); getchar(); return 0;}
4. 兩個整數相除只返回整數:
#include <stdio.h>int main(void){ int n1 = 3; int n2 = 2; float f; /* 這樣不行; 但如果你本來就只想要整數部分, 那不正中下懷嗎? */ f = 3 / 2; printf("%g\n", f); /* 這樣才可以(如果只有兩個運算數, 其中一個是浮點數即可, 但多了不行) */ f = 3.0 / 2.0; printf("%g\n", f); /* 這樣不行 */ f = n1 / n2; printf("%g\n", f); /* 這樣也不行 */ f = (float)(n1 / n2); printf("%g\n", f); /* 這樣才可以 */ f = (float)(n1) / (float)(n2); printf("%g\n", f); getchar(); return 0;}