C 中的数字频率问题,无法获得大输入的正确频率
Digit Freqency Problem in C, Not getting correct frequency for large input
问题是获取给定输入字符串中数字的频率
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
char s[1000];
scanf("%s", s);
int index = 0;
int len=strlen(s);
int count[10] = {0};
while(index!=len){
//printf("%c",s[index]);
count[s[index++] - 48]++;
}
for(int i = 0; i < 10; i++)
printf("%d ", count[i]);
return 0;
}
当给定小字符串输入时它可以工作,但对于以下输入
8g614eggv7n388564l82nl6f35826hrzd533380b7870n4954497308f03wsx6zyr45025845zz55x7576631425l311cj4n9u29f4xje02l35t31m6me078bx421c24cocx83e438g88d069cc39bn6292033q055kk81m4f82798h7pt031mv530g4v7519h6g78z34p228f9z6067emv47e83uj805q805d572k18h077q6zzo22f35k22631l5j6n8fz0u583xkuu392613478x8823119241o6802910551sm8w9or6v78443c8wt63i3ft21d548p79h14i26k65qhbs79h65su27l1waz62m7l155bib1a2w401b8j7s2i719i68tr60492f685g7lx96i077775kq9436s6s6h81f827624583m894314vjvd41385ww0639e6xs8wzn6362a0029233j99097be0124408o90c861281jgu3168765af270z47e208bclp3845799e4p2710i231h
我得到的输出为
32 32 39 37 34 34 40 37 46 30
但实际输出是
32 33 40 40 35 35 39 36 48 29
我哪里错了
s[index++] - 48
——如果s[index++]
是'a',结果是97 - 48,是49。count[49]
是越界访问,导致undefined行为。
正如另一个中提到的,由于缓冲区溢出,程序中存在未定义的行为。
我建议在使用 isdigit()
函数更新 count
之前过滤掉非数字。
#include <ctype.h>
...
char c = s[index++];
if (isdigit(c))
count[c - '0']++;
问题是获取给定输入字符串中数字的频率
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
char s[1000];
scanf("%s", s);
int index = 0;
int len=strlen(s);
int count[10] = {0};
while(index!=len){
//printf("%c",s[index]);
count[s[index++] - 48]++;
}
for(int i = 0; i < 10; i++)
printf("%d ", count[i]);
return 0;
}
当给定小字符串输入时它可以工作,但对于以下输入
8g614eggv7n388564l82nl6f35826hrzd533380b7870n4954497308f03wsx6zyr45025845zz55x7576631425l311cj4n9u29f4xje02l35t31m6me078bx421c24cocx83e438g88d069cc39bn6292033q055kk81m4f82798h7pt031mv530g4v7519h6g78z34p228f9z6067emv47e83uj805q805d572k18h077q6zzo22f35k22631l5j6n8fz0u583xkuu392613478x8823119241o6802910551sm8w9or6v78443c8wt63i3ft21d548p79h14i26k65qhbs79h65su27l1waz62m7l155bib1a2w401b8j7s2i719i68tr60492f685g7lx96i077775kq9436s6s6h81f827624583m894314vjvd41385ww0639e6xs8wzn6362a0029233j99097be0124408o90c861281jgu3168765af270z47e208bclp3845799e4p2710i231h
我得到的输出为 32 32 39 37 34 34 40 37 46 30
但实际输出是 32 33 40 40 35 35 39 36 48 29
我哪里错了
s[index++] - 48
——如果s[index++]
是'a',结果是97 - 48,是49。count[49]
是越界访问,导致undefined行为。
正如另一个
我建议在使用 isdigit()
函数更新 count
之前过滤掉非数字。
#include <ctype.h>
...
char c = s[index++];
if (isdigit(c))
count[c - '0']++;