计算字符数组中的个数
Count number of ones in a array of characters
我正在尝试使用递归类型程序计算表示二进制数的字符数组中的个数。但是,似乎我的程序只是在计算数组中的字符数。我不知道我是不是只是比较错误,但我似乎找不到问题
#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] != '[=10=]')
{
if ( array[track] == '1');
{
count++;
}
return determine(array, count, track = track+1);
}
else
{
return count;
}
}
在方法中 determine()
:
if ( array[track] == '1');
去掉分号;
。分号使 if
条件执行 empty
块。所以 count++
将始终执行 if
条件是否成功(true
)或不成功(false
)。
我 运行 你的代码 ;
并得到输出:
The number of 1's is 7
没有;
:
The number of 1's is 3
if ( array[track] == '1');
应该是
if ( array[track] == '1')
删除 ;
如果你有 ;
那么无论条件评估结果如何(真或假)count++
都会被执行
你试过简单的countif函数吗?
=sum if (range="1")
我正在尝试使用递归类型程序计算表示二进制数的字符数组中的个数。但是,似乎我的程序只是在计算数组中的字符数。我不知道我是不是只是比较错误,但我似乎找不到问题
#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] != '[=10=]')
{
if ( array[track] == '1');
{
count++;
}
return determine(array, count, track = track+1);
}
else
{
return count;
}
}
在方法中 determine()
:
if ( array[track] == '1');
去掉分号;
。分号使 if
条件执行 empty
块。所以 count++
将始终执行 if
条件是否成功(true
)或不成功(false
)。
我 运行 你的代码 ;
并得到输出:
The number of 1's is 7
没有;
:
The number of 1's is 3
if ( array[track] == '1');
应该是
if ( array[track] == '1')
删除 ;
如果你有 ;
那么无论条件评估结果如何(真或假)count++
都会被执行
你试过简单的countif函数吗?
=sum if (range="1")