用于大输入的数字频率程序
我编写了以下程序,以找出每个数字在字符数组中出现的次数。
int main(){ char s[2000],count,j=0; fgets(s,2000,stdin); for(int i=0;i<=9;i++) { count=0;j=0; while(*(s+j)) { if(isdigit(*(s+j))) { if(i==(*(s+j)-'0')) count++; } j++; } printf("%d ",count); } return 0; }
但它不适合大量投入。
b3n47b5xf13qlx233rg4u2c949i623e34nt5661se06b675utbpy258wz633855846l761d61x340h1vn19w191sj18v2u333556bh6m5uc4u050am05p961dhmpu6iq4667zg9
预期的产出是
5 10 5 12 8 11 15 4 4 6
但我得到的输出是
5 10 5 12 7 11 13 3 4 5
任何人都可以帮助我找到我出错的地方吗?
除了DYZ的答案,你的逻辑也很复杂。 你不需要测试if(isdigit(*(s+j)))
和if(i==(*(s+j)-'0'))
,你只需要重构代码并提供一个单次测试并使用频率数组。
(一个简单的数组,其中10个元素初始化为全零,其中当找到该数字时,增加与每个数字对应的索引,导致该数字的计数在完成时出现在相应的索引处)
#include #include #define MAXC 2048 /* if you need a constant, #define one (or more) */ #define NDIGIT 10 int main (void) { char s[MAXC] = ""; size_t digits[NDIGIT] = {0}; /* declare a 'frequency array' */ while (fgets (s, MAXC, stdin)) { /* read all blocks of data */ char *p = s; /* pointer to s */ while (*p) { /* for each char in s */ if (isdigit (*p)) /* Am I a digit? */ digits[*p - '0']++; /* increment value at index */ p++; /* increment pointer */ } } for (int i = 0; i < NDIGIT; i++) printf (" %zu", digits[i]); putchar ('\n'); return 0; }
或者没有ctype.h
,
#include #define MAXC 2048 /* if you need a constant, #define one (or more) */ #define NDIGIT 10 int main (void) { char s[MAXC] = ""; size_t digits[NDIGIT] = {0}; /* declare a 'frequency array' */ while (fgets (s, MAXC, stdin)) { /* read all blocks of data */ char *p = s; /* pointer to s */ while (*p) { /* for each char in s */ if ('0' <= *p && *p <= '9') /* Am I a digit? */ digits[*p - '0']++; /* increment value at index */ p++; /* increment pointer */ } } for (int i = 0; i < NDIGIT; i++) printf (" %zu", digits[i]); putchar ('\n'); return 0; }
示例使用/输出
在这两种情况下,输入的输出是:
5 10 5 12 8 11 15 4 4 6
仔细看看,如果您有其他问题,请告诉我。
你将j
声明为char
(并count
,但它是一个不同的问题)。 (带符号) char
变量的最大值为127.当字符串超过128个字符时, j
溢出: j+1
变为-128而不是128.声明用于索引和计数的所有变量为int
或size_t
。