我尝试编写一个程序来计算给定字符串中给定字符的出现次数。
以下是该计划:
#include <stdio.h>
#include <string.h>
int find_c(char s[], char c)
{
int count;
int i;
for(i=0; i < strlen(s); i++)
if(s[i] == c)
count++;
return count;
}
int main()
{
int number;
char s[] = "fighjudredifind";
number = find_c(s, 'd');
printf("%d\n",number);
return 0;
}
我期待以下输出:
3
因为字符串s中字符“d”的出现次数是3。
每次我尝试运行程序时,屏幕上都会显示不同的数字。例如,我在运行程序时得到以下输出:
-378387261
在另一次运行程序时获得此输出:
141456579
为什么我输错了输出?我该如何解决?
提前致谢!
答案 0 :(得分:2)
在C中整数不会自动初始化为零。
问题是count
变量未初始化
尝试将count
函数中的find_c
变量初始化为零。
答案 1 :(得分:2)
嗯,你的代码很好。唯一的错误是,您没有将计数初始化为0.如果您没有初始化变量将保留垃圾值,您将对该值执行操作。因此,在前面的情况下,每次执行程序时都会获得所有垃圾值。
以下是代码:
#include <stdio.h>
#include <string.h>
int find_c(char s[], char c) {
int count=0;
int i;
for(i=0; i < strlen(s); i++)
if(s[i] == c)
count++;
return count;
}
int main() {
int number;
char s[] = "fighjudredifind";
number = find_c(s, 'd');
printf("%d\n",number);
return 0;
}