Welcome

首页 / 软件开发 / C语言 / 学点C语言(17):数据类型 - 因类型引发的问题或错误

学点C语言(17):数据类型 - 因类型引发的问题或错误2010-04-30 博客园 万一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 ",num1);

/* 这样可以了 */
num2 = s1 + s2;
printf("%d ",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 ",n1,n2,n3);
printf("%#X,%#X,%#X ",n1,n2,n3);

n1 = LLONG_MAX;
printf("%lld,%u ",LLONG_MAX,n1);
printf("%#llx,%#x ",LLONG_MAX,n1);

getchar();
return 0;
}

3. 把浮点数赋给整数:

#include <stdio.h>

int main(void)
{
double pi = 3.14159265;
int i;

/* 只会留下整数部分 */
i = pi;
printf("%d ",i);

/* 并且不会四舍五入 */
i = 3.6;
printf("%d ",i);

getchar();
return 0;
}