10分)编写一个程序,将用户输入的十进制短整型正数n转换成二进制数。如果用户输入负数或者读入错误,则要求用户重新输入。
输入提示信息:"n="
**输入格式:"%hd" /* short 类型 /
输出信息:"the binary number is "
*输出格式要求:"%d"
程序运行示例如下:
n=37
the binary number is 0000000000100101
小妹的程序代码如下:
#include
int main()
{
printf("n=");
short int n;
do
{
scanf("%hd",&n);
}while(scanf("%hd",&n)!=1||n<0);
printf("the binary number is ");
while(n!=1)
{
printf("%d",n%2);
n=n/2;
}
printf("%d",n);
return 0;
}
输入之后好像没反应的啦!求大神指教。
小妹跪求大神指教一下,谢谢!
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
T_world 2017-05-21 06:52关注你用一个do-while循环处理输入,判断条件是输入,循环体还是输入,这样很可能就会无限输入下去,最好是用一个循环包括整个过程,每次有输入就处理一次输入的情况,根据你的代码修改如下:
#include<stdio.h> int main() { short int n; while(true) { printf("n="); scanf("%hd",&n); if(n<0) { continue; printf("Please input again!"); } printf("the binary number is "); while(n!=1) { printf("%d",n%2); n=n/2; } printf("%d",n); printf("\n"); } return 0; }当然了,按照你现在的实现算法,计算出来的二进制数字是反过来的,你可以再想个办法让二进制数正过来,这件事也不难
评论 打赏 举报解决 2无用