【问题标题】:Why did I get the wrong output and how can I fix this?为什么我得到了错误的输出,我该如何解决这个问题?
【发布时间】:2017-02-25 16:34:58
【问题描述】:

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

这是程序:

#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

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

提前致谢!

【问题讨论】:

  • 循环开始前的计数值是多少?
  • @stark 我猜它是 0,因为 int 在 C 中默认初始化为零
  • 非静态局部(又名自动)变量未初始化,其值为indeterminate。在没有初始化的情况下使用它们会导致未定义的行为
  • 自动变量包含堆栈上最后的任何垃圾
  • @某程序员老兄 谢谢!我将 count 初始化为 0 并解决了问题。

标签: c string output character reverse


【解决方案1】:

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

【讨论】:

  • 非常感谢您清晰详细的解释它成功了!
  • @sreepurna 当然,实际上我已经这样做了 :) 谢谢!
  • @sreepurna 是的,你是对的。我刚刚标记了它:) 你刚刚教会了我一些新东西。谢谢!
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2015-06-13
    • 2021-09-19
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 2021-07-01
    相关资源
    最近更新 更多