简体   繁体   English

计算字符数组中的1的数量

[英]Count number of ones in a array of characters

I am trying to count the number of ones in an array of characters that represent a binary number with a recursive type program. 我试图用递归类型程序计算表示二进制数的字符数组中的1的数量。 However, it seems as if my program is just counting the number of characters in the array. 但是,似乎我的程序只是计算数组中的字符数。 I do not know if I am just comparing wrong or not but I can't seem to find the problem 我不知道我是否只是在比较错误与否,但我似乎无法找到问题

#include <stdio.h>
# include <stdlib.h>
#include <string.h>
#define SIZE 20

int determine (char array[SIZE], int count, int track );

int main()
{ 
int answer = 0; 
char input[SIZE]={"1001001"};
int count = 0;
int track = 0;

answer = determine(input, count, track);

 printf("The number of 1's is %d ", answer);

system("PAUSE");
return 0;
 }

 int determine(char array[], int count, int track)
{   

 if (array[track] != '\0')
 {
    if ( array[track] == '1');
    {
         count++;
    }
    return determine(array, count, track = track+1);    
 }
 else 
 {
      return count;
 }
}

In method determine() : 在方法determine()

if ( array[track] == '1');

remove the semicolon ; 删除分号; . The semicolon makes the if condition to execute an empty block. 分号使if条件执行empty块。 So the count++ will always execute whether the if condition succeeded( true ) or not( false ). 因此count++将始终执行if条件是否成功( true )或不成功( false )。

I run your code with ; 我运行你的代码; and get the output: 并得到输出:

The number of 1's is 7 1的数量是7

And without ; 没有; :

The number of 1's is 3 1的数量是3

if ( array[track] == '1');

should be 应该

if ( array[track] == '1')

remove the ; 删除;

If you have the ; 如果你有; then irrespective of the condition evaluation result (TRUE or FALSE) count++ will get executed 然后不管条件评估结果(TRUE或FALSE) count++将被执行

Have you tried a simple countif function? 你试过一个简单的countif功能吗?

=sum if (range="1") = sum if(range =“1”)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM