

以下是我代碼:
#include <stdio.h>
#include <math.h>
int main()
{
unsigned int x,n;
int i,y;
char s[50];
scanf("%u",&x);
i=0;
while(x>0)
{
s[i++]=x%2+'0';
x=x/2;
}
s[i]='\0';
y=i-1;
for(i=y;i>=0;i--) if((i+1)%2==0) s[i]='0';
for(i=y,n=0;i>=0;i--) n+=pow(2.0,y-i)*(s[i]-'0');
printf("%u\n",n);
return 0;
}
uj5u.com熱心網友回復:
需要這么復雜嗎?用&運算就好了呀?二進制1010就是16進制a
所以
y = x & 0xaaaaaaaa
就可以了
uj5u.com熱心網友回復:
#include <stdio.h>
#include <math.h>
unsigned int get_odd_bit(unsigned int n, int bit_len);
int main()
{
#if 0
unsigned int x,n;
int i,y;
char s[50];
scanf("%u",&x);
i=0;
while(x>0)
{
s[i++] = x%2 +'0';
x=x/2;
}
s[i]='\0';
puts(s);
y = i-1;
for(i=y;i>=0;i--) if((i+1)%2==0) s[i]='0';
puts(s);
for(i=y,n=0;i>=0;i--) n+=pow(2.0,y-i)*(s[i]-'0');
printf("%u\n",n);
#else
unsigned int x;
scanf("%u", &x);
x = get_odd_bit(x, 32);
printf("%u\n", x);
#endif
return 0;
}
unsigned int get_odd_bit(unsigned int n, int bit_len)
{
unsigned int s = 0;
int i;
for (i = 0; i < bit_len; i++) {
if (i % 2)
s += ((n >> i) & 1u) ? (1u << i) : 0;
}
return s;
}
供參考
樓主的代碼是沒問題的,但是不符合題目要求。因為題目要求自定義函式實作,樓主把邏輯都寫在main函式里。
建議樓主把自己的邏輯用一個自定義函式來實作試試。以上是自己用自定義函式來實作的,參考一下
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/258217.html
標籤:C語言
