zoukankan      html  css  js  c++  java
  • C语言练习之 计算数据中“1”的个数

      最近在研究串口发送数据的奇偶校验,受到了一些启发,就想写一个计算发送数据中“1‘的个数的程序,

    刚好笔者最近在学习《C和指针》所以就想记录下来,方便自己查阅,说不定,将来还可以直接赋值使用。

     1 #include <string>
     2 #include<iostream>
     3 
     4 using namespace std;
     5 
     6 int count_one_bits(unsigned value); //统计value中"1"的个数
     7 
     8 int main(int argc, char *argv) {
     9 
    10     int a,count;
    11     scanf("%d", &a);
    12     count=count_one_bits(a);
    13     printf("%d中1的个数是%d
    ",a,count);
    14     
    15     return 0;
    16     
    17 
    18 }
    19 
    20 int count_one_bits(unsigned value) {
    21     unsigned int ones;
    22     for (ones = 0; value != 0; value >>= 1) {
    23         if ((value & 1) != 0) {
    24             ones += 1;   //ones 最低位为1,增加计数器的值
    25         }
    26     }
    27 
    28     return ones;
    29 }
    View Code

    在vs2015上面运行如图所示:

  • 相关阅读:
    3.24
    3.23
    构建之法读书笔记2
    寒假学习day23
    寒假学习day22
    寒假学习day21
    寒假学习day20
    寒假学习day19
    寒假学习每周总结4
    寒假学习day18
  • 原文地址:https://www.cnblogs.com/xuelanga000/p/11381677.html
Copyright © 2011-2022 走看看