简体   繁体   English

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

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

I tried to write a program to count the number of occurrences of a given character in a given string. 我试图编写一个程序来计算给定字符串中给定字符的出现次数。

Here's the program: 这是程序:

#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;
}

I was expecting the following output: 我期待以下输出:

3

since the number of occurrences of the character 'd' in the string s is 3. 因为字符串s中字符“ d”的出现次数为3。

Each time I tried to run the program, a different number was displayed on the screen. 每次我尝试运行该程序时,屏幕上都会显示一个不同的数字。 For example, I got the following output while running the program one time: 例如,一次运行该程序时得到以下输出:

-378387261

And got this output, when running the program another time: 并在再次运行该程序时得到了此输出:

141456579

Why did I get the wrong output and how can I fix this? 为什么我得到了错误的输出,我该如何解决?

Thanks in advance! 提前致谢!

In C Integers are not automatically initialized to zero. 在C中,整数不会自动初始化为零。 The problem is that the count variable is not initialized. 问题是count变量未初始化。
Try initializing the count variable in the find_c function to zero. 尝试将find_c函数中的count变量初始化为零。

Well, Your code is good. 好吧,您的代码是好的。 Only mistake is, you did not initialize the count to 0. If you do not initialize the variable will hold the garbage value and you will be performing operations on that value. 唯一的错误是,您没有将计数初始化为0。如果不初始化,变量将保存垃圾值,并且您将对该值执行操作。 As a result, in the earlier case, you got all the garbage values, when you execute the program each time. 结果,在较早的情况下,每次执行程序时,您都会获得所有垃圾值。

Here is the code: 这是代码:

#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;
}

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

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