我试图编写一个程序来计算给定字符串中给定字符的出现次数。
这是程序:
#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
为什么我得到了错误的输出,我该如何解决这个问题?
提前致谢!
嗯,你的代码很好。唯一的错误是,您没有将计数初始化为 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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句