@C语言大神:我代码的输入格式哪里不对?求解释、

# include<stdio.h>int main(){char system;int n,remain,result;printf("input a number:\n");scanf("%d",&n);printf("input a system:\n");scanf("%c\n",&system);//这里按理说输入的是字母,调试时不是,why? printf("the new number is:\n");//上一步到底哪里错了啊? if(result!=0&&system=='B'){ remain=n%2; result=n/2; printf("%3d",remain); n=result;}else if(result!=0&&system=='O'){ remain=n%8; result=n/8; printf("%3d",remain); n=result;}else if(result!=0&&system=='H'){ remain=n%16; result=n/16; printf("%3d",remain); n=result;}else{ printf("wrong character or 0,input again.\n");}
getch();}

第1个回答  推荐于2016-10-18
# include<stdio.h>
int main()
{
char system;
int n,remain,result;
printf("input a number:\n");
scanf("%d",&n);
fflush(stdin);//在输入第一个数字之后,缓存区里还有一个字符'\n',根据scanf的机制,下一次输入的时候会对缓存区的'\n'匹配,而'\n'恰好也是一个字符,所以system='\n',这个函数是用来清除缓存区
printf("input a system:\n");
scanf("%c",&system);//对了这的“%c\n”中的\n要删去,否则在输入的时候会出问题
printf("the new number is:\n");//上一步到底哪里错了啊?
if(result!=0&&system=='B')
{ remain=n%2;
result=n/2;
printf("%3d",remain);
n=result;
}
else if(result!=0&&system=='O')
{ remain=n%8;
result=n/8;
printf("%3d",remain);
n=result;
}
else if(result!=0&&system=='H')
{ remain=n%16;
result=n/16;
printf("%3d",remain);
n=result;
}
else
{ printf("wrong character or 0,input again.\n");
}
return 0;
}追问

可是输入语句没用\n的话还是不对啊???

加了fflush还是没有用,为什么

追答

# include
int main()
{
char system,free;
int n,remain,result;
scanf("%d%c%c",&n,&free,&system);
printf("the new number is:\n");//上一步到底哪里错了啊?
if(result!=0&&system=='B')
{ remain=n%2;
result=n/2;
printf("%3d",remain);
n=result;
}
else if(result!=0&&system=='O')
{ remain=n%8;
result=n/8;
printf("%3d",remain);
n=result;
}
else if(result!=0&&system=='H')
{ remain=n%16;
result=n/16;
printf("%3d",remain);
n=result;
}
else
{ printf("wrong character or 0,input again.\n");
}
return 0;
}
这是满足你这道题目的输入方式

追问

我原来的程序添加查看的时候,B system是这个,为什么啊?

追答

66是字符B对应的ASCII码

追问

为什么会出现ASCII码?那后面用if判断的时候怎么写?

跪求解释

追答

你现在这样写是没有错误的,每一个字符都有一个对于的ASCII码,你可以自行百度ASCII码表,因为char类型可以强制转换为int类型
比如:
char a = 'B';
int b = (int)a;
此时b就变成了66

追问

但是执行不了啊

system我输入的是B,但是程序在判断的时候就不是B可

怎么办

追答

不会吧,我本地检验了一下,是可以执行的

追问

骗人的吧,截图来啊

追答

这是你的程序的执行效果

追问

在来几个输入输出??

再来几个试试

可能我们编译器不同

本回答被提问者采纳
第2个回答  2015-05-05
scanf("%c\n",&system);改为scanf("%c",&system);这是输入函数,转义字符是在输出的时候用的追问

不是啊 还是不对

追答

那你再在scanf("%c",&system);的前面加个清除缓存的试试fflush(stdin);

追问

还是不对啊