C語言入門---⑦
阿新 • • 發佈:2018-10-31
//1.
//寫一個函式返回引數二進位制中 1 的個數
//比如: 15 0000 1111 4 個 1
#include<stdio.h> #include<stdlib.h> int count_one_bits(unsigned int value) { int count = 0; int one = 0; // 返回 1的位數 while (value!=0){ one = value % 2; if (one == 1){ ++count; } value = value / 2; } return count; } int main(){ printf("%d\n",count_one_bits(15)); system("pause"); return 0; }
//2.獲取一個數二進位制序列中所有的偶數位和奇數位,
//分別輸出二進位制序列。
#include<stdio.h> #include<stdlib.h> // void print_num(unsigned value) { int count = 0;//計算二進位制 位數 int a[32] = { 0 }; int i = 0; while (value) { a[i++] = value % 2; value /= 2; count++; } printf("奇數序列\n"); for (i = count; i >= 0; i -= 2) { printf("%d ", a[i]); } printf("\n"); printf("偶數序列\n"); for (i = count - 1; i >= 0; i -= 2) { printf("%d ", a[i]); } printf("\n"); } int main() { printf("獲取一個數二進位制序列中所有的偶數位和奇數位,分別輸出二進位制序列(測試數字01011)\n"); int value = 11;//01011 print_num(value); system("pause"); return 0; }
4.程式設計實現:
//兩個int(32位)整數m和n的二進位制表達中,有多少個位(bit)不同?
//輸入例子 :
//1999 2299
//輸出例子 : 7
#include<stdio.h> #include<stdlib.h> int Bit_Diff(int m, int n){ int i = 0; int m_bit[32] = { 0 }; int count_m = 0; int n_bit[32] = { 0 }; int count_n = 0; int count = 0; while (m){ m_bit[count_m++] = m % 2; m /= 2; } while (n){ n_bit[count_n++] = n % 2; n /= 2; } for (int i = count_m; i >= 0; i--){ printf("%d\t", m_bit[i]); } printf("\n"); for (int j = count_n; j >= 0; j--){ printf("%d\t", n_bit[j]); } while (1){ if (m_bit[i] != n_bit[i]){ count++; } if (i == count_m-1){ count += (count_n - count_m); break; } i++; } return count; } int main(){ printf("%d",Bit_Diff(1999, 2299)); system("pause"); return 0; }