为什么我得到错误的输出,我该如何解决这个问题?

Why did I get the wrong output and how can I fix this?

我尝试编写一个程序来计算给定字符串中给定字符的出现次数。

程序如下:

#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

因为字符'd'在字符串s中出现的次数为3.

每次我尝试 运行 程序时,屏幕上都会显示不同的数字。例如,我 运行 运行程序一次时得到以下输出:

-378387261

并得到这个输出,当 运行另一次调用程序时:

141456579

为什么我得到了错误的输出,我该如何解决这个问题?

提前致谢!

在 C 中,整数不会自动初始化为零。 问题是 count 变量没有初始化。
尝试将 find_c 函数中的 count 变量初始化为零。

嗯,你的代码很好。唯一的错误是,您没有将计数初始化为 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;
}