为什么将int换成char,结果就不一样了。

这是求三个数中的最大数
#include <reg52.h>
#include <stdio.h>

void uart_init()
{
SCON = 0x50;
TMOD =(TMOD & 0xf)/ 0x20;
TH1 = 221;
TR1 =1;
TI =1;
}
int max(int a,int b,int c)
{ int temp;
temp=a>b?a:b;
temp=temp>c?temp:c;
return temp;
}
void main()
{
int x=10,y=40,z=30,f=50,result=0;
uart_init();
result=max(x,y,z);
printf("x=%d,y=%d,z=%d,",x,y,z);
printf("\nthe largest number is %d.",result);
while (1)
{}
}
最后输出:
X=10,Y=40,Z=30,
The largest number is 40.
如果我装文中所有出现过的int 换成char后,
#include <reg52.h>
#include <stdio.h>

void uart_init()
{
SCON = 0x50;
TMOD =(TMOD & 0xf)/ 0x20;
TH1 = 221;
TR1 =1;
TI =1;
}
char max(char a,char b,char c)
{ char temp;
temp=a>b?a:b;
temp=temp>c?temp:c;
return temp;
}
void main()
{
char x=10,y=40,z=30,f=50,result=0;
uart_init();
result=max(x,y,z);
printf("x=%d,y=%d,z=%d,",x,y,z);
printf("\nthe largest number is %d.",result);
while (1)
{}
}
最后输出:
X=2600,Y=7680,Z=0,
The largest number is 10280.

char是字符类型的,首先你的定义就有点问题,其次直接按整型方式输出字符型变量,程序会默认将字符型变量按ASCII编码 转换后再输出。追问

也就是说我要想用到printf输出,就要定义int变量。那我现在用char,为什么结果是2600呢。这个怎么来的,就算按字符转ASCII那也应该是3130才对啊,还请指教一下。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-03-06
输出时用的格式串错了,把%d改为%c就行了追问

那也不行啊:
结果变成:
X=
,Y=(,Z=,
the largest number is (.

第2个回答  2012-03-07
没问题,我亲自验证了。看看是不是此程序与其他程序在一起执行呀?把工作空间关了,然后重新运行,看看可以吗。
相似回答