[英]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
因为字符串s中字符“ d”的出现次数为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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.