scanf("%d",&n);
while(n>0)
t = n%2;
n = n/2;
printf("%d\n",x);
[1] &n
[2] n > 0
[3] n % 2
[4] n / 2
[5] x
#include <stdio.h>
int main()
{
int n,x,t;
printf("请输入一个整数:");
scanf("%d",&n);
x = 0;
while(n > 0) {
t = n % 2;
n = n / 2;
x = x*2+t;
}
printf("%d\n", x);
return 0;
}
显然,这是从右到左获取输入整数的二进制位,然后从左到右拼接成新的整数
根据x=0
,x = x*2+t;
可以看出x是拼接后的整数,t是每次取得的二进制位,这样把之前的数*2,在加上t就相当于把t拼接在之前的二进制序列后面
#include <stdio.h>
int main()
{
int n,x,t;
scanf("%d",&n);
x = 0;
while(n != 0) {
t = n%2;
n = n/2;
x = x*2+t;
}
printf("%d",x);
return 0;
}
#include<stdio.h>
main()
{
int n,x,t;
printf("请输入");
scanf("%d",&n);
x=0;
while(n!=0){
t=n%2;
n=n/2;
x=x*2+t;
}
printf("%d\n",x);
}
如果有帮助请点一下我回答右上方的采纳,谢谢!以后有什么问题可以互相交流。