char和int类型转换问题询问

sito 2002-09-07 11:55:07
#include "stdio.h"
void select(int i)
{
switch(i)
{
case 1:
printf("You select 1\n");
break;
case 2:
printf("you select 2\n");
break;
case 3:
printf("you select 3\n");
break;
default:
printf("default executing\n");
}
}
main()
{
char ch;
ch=getchar();
int a=(int)ch;
select(a);
printf("%d\n", sizeof (int)ch);
return 0;
}

我已经把ch转换成了年int型,为什么我无论输入什么字符都执行default
...全文
149 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
snwcwt 2002-09-07
  • 打赏
  • 举报
回复
你在键盘上输入0,1,2,3,4,5,6,7,8,9的数字是以字符接受的,它们的ASCII码是30-39,你把ch转换为int型后,a中的数字实际上是30-39中的一个数字,所以肯定都是执行default里面的语句了。

printf("%d\n", sizeof (int)ch);
vc下int是4个字节不是2,TC2中才是哈。
max_welcome 2002-09-07
  • 打赏
  • 举报
回复
你输入的是字符,你查一下ascii码,字符的值基本都大于1,2,3当然要执行
default了
metero 2002-09-07
  • 打赏
  • 举报
回复
char是1个字节
short是2个字节
int是4个字节
double是8个字节
metero 2002-09-07
  • 打赏
  • 举报
回复
ch=getchar();它的值一般在32-128之间,所以,你转成int之后也是这么多。
你可以这样:

default: printf("default : %d\n",i);
看一下。

sito 2002-09-07
  • 打赏
  • 举报
回复
我是在vc6.0中编译的
printf("%d\n", sizeof (int)ch);
为什么会打印 4 啊,int不是2个字节吗?
Lute 2002-09-07
  • 打赏
  • 举报
回复
你将一个char通过(int)char的方式进行强制转换的得到的结果是该char的
ASCII码如char a='1';
int b=(int)a;
printf("%d",b);
则你会看到b的值是49而不是你想象中的1,由于你没在swich(int i)中定义i=49时做什么那么,处理它的工作便自然交给了efault去完成了,为达成你的目的你应用函数 int atoi(char *str),或编一个类似的函数来做转换工作
honeybe 2002-09-07
  • 打赏
  • 举报
回复
atoi(char *)

转换一下啊
glassshark 2002-09-07
  • 打赏
  • 举报
回复
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>

void select(int i)
{
switch(i)
{
case '1':
printf("You select 1\n");
break;
case '2':
printf("you select 2\n");
break;
case '3':
printf("you select 3\n");
break;
default:
printf("default executing\n");
}
}

int main()
{
char ch;
ch=getchar();
int a=(int)ch;
select(a);
printf("%d\n", sizeof((int)ch));
system("pause");
return 0;
}

paulxj 2002-09-07
  • 打赏
  • 举报
回复
字符的ascii吗没有等于1,2,3的。那当然是default了
prototype 2002-09-07
  • 打赏
  • 举报
回复
int a=ch - '0';

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧