编写一个 C 函数,该函数给出一个字节中被置1 的位的个数。

[复制链接]
查看11 | 回复4 | 2007-9-3 15:43:42 | 显示全部楼层 |阅读模式
int ch(char a){ int i,cnt=0; int mask=1<<7;for (i=0; i<7; i++)
{
if ((a&mask)!=0)cnt++; a<<=1;
} return cnt;}
回复

使用道具 举报

千问 | 2007-9-3 15:43:42 | 显示全部楼层
二楼(回答者:garfield0 - 试用期 一级),你好像些错了吧应该这样的:#include "stdio.h" int rest(int x){int i,y,sum=0;for (i=0;i<8;i++){y=x%2; /*这是移出去的值*/x=x/2; /*对于整数右移一次后x的值相当于右移前的值除以2。*/if (y==1) sum+=1;}return sum;}int main(){int x;scanf("%d",&x);/*输入的值应该在0-255之间,利于检验。*/printf("%d",rest(x));return 0;}
回复

使用道具 举报

千问 | 2007-9-3 15:43:42 | 显示全部楼层
for 循环 8次字节右移一位模2取余是1则 sum++最后sum就是1的个数
回复

使用道具 举报

千问 | 2007-9-3 15:43:42 | 显示全部楼层
int rest(int x){int i;i=strlen(x);for (i=0;i<8;i++){y=x%2; if (y=1) sum+=1; else coutinue; }return sum;}根据楼上仁兄写的,但我还 是不明白你这个函数的作用是什么?
回复

使用道具 举报

千问 | 2007-9-3 15:43:42 | 显示全部楼层
不用那么麻烦intbit1count(charx){intres=0;while(x&=(x-1))++res;returnres;}x&(x-1)的作用是每次把x二进制写法中最右的一个1去掉,去一个res+1这样去直到x为0,就是没1了为止。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行