C中的频率功能
发布时间:2020-12-16 03:47:07 所属栏目:百科 来源:网络整理
导读:我写了一个程序,它应该取一个字符串和一个字母,然后调用一个函数,它有两个参数(字符串,字母),然后计算字符串中字母的频率. 我的代码的问题是它总是为任何字母返回值为零的num. #include stdio.h#include stdlib.hint Occur(char [],char);int main(){ char s
我写了一个程序,它应该取一个字符串和一个字母,然后调用一个函数,它有两个参数(字符串,字母),然后计算字符串中字母的频率.
我的代码的问题是它总是为任何字母返回值为零的num. #include <stdio.h> #include <stdlib.h> int Occur(char [],char); int main() { char s[100],l; printf("Enter A String:n"); scanf("%s",s); printf("Enter A Letter:n"); scanf("%c",&l); getchar(); printf("Num Of Occurance is %d ",Occur(s,l)); return 0; } int Occur(char S[100],char L) { int i; int num=0; for(i=0; S[i]!=' '; i++) { if(S[i]==L) num++; } return num; } 解决方法
问题原因:
scanf(“%c”,& l)//这里%c接受scanf的输入键(“%s”,s);; 所以,你的问题主要有2个解决方案: 索尔. 1 => scanf(“%c”,& l)//在%c之前使用空格 索尔. 2 =>使用fflush(stdin)刷新流的输出缓冲区. int main() { char s[100],l; printf("Enter A String:n"); scanf("%s",s); printf("Enter A Letter:n"); fflush(stdin); //here fflush(stdin) used to flushes the output buffer. scanf("%c",&l); l = getchar(); ...... ...... } 注意:由于fflush(stdin)具有未定义的行为,因此始终优先使用Solution 1,而不是fflush(). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |