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;
}


posted on 2008-11-27 13:38  万一  阅读(1464)  评论(0编辑  收藏  举报