gpt4 book ai didi

c - 尝试计算字母频率时的无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 02:46:32 25 4
gpt4 key购买 nike

#include <stdio.h>
#include <string.h>

int main(void)
{
char string[100];
int c = 0, count[26] = {0};
int accum = 0;
int a;

while(1)
{
a = scanf("%s", string);
while ( string[c] != '\0' )
{

if ( string[c] >= 'a' && string[c] <= 'z' ){
count[string[c]-'a']++;
accum++;
}

else if (string[c] >= 'A' && string[c] <= 'Z'){
count[string[c]-'A']++;
accum++;
}
c++;
}
if (a == EOF)
{
for ( c = 0 ; c < 26 ; c++ )
{
if( count[c] != 0 )
printf( "%c %f\n", c+'a', ((double)count[c])/accum);
}
}
}
return 0;
}

所以我有一个程序可以计算 EOF 之前出现在标准输入中的字母的频率。但是一旦我到达 EOF,我的程序就会进入无限循环并且频率似乎不正确。当我只输入一个打印语句来输入一个字符串时,它工作正常。我真的不知道问题出在哪里。有人能帮我解决这个问题吗?

最佳答案

if (a == EOF) 应该紧跟在 a = scanf("%s", string);

之后

那么 if() 条件应该存在于循环中。

每次循环都应该重置c = 0

while(1) {
a = scanf("%s", string);
if (a == EOF) {
...
break;
}
c = 0;
while ( string[c] != '\0' ) {

通过上述更改,相信您的代码会正常运行。在较小程度上还有其他事情需要考虑。 1) scanf("%s",... 是无界的。2) 应该限制输入。 if (a == EOF) 也可以在循环之后编码。 3) 提示循环条件为scanf()==1的肯定肯定。在好的情况下循环,而不是在坏的情况下退出。 4) 考虑使用 unsignedint 进行计数。 5) for() 循环比 while() 更适合增量循环。 6) 避免像 26 这样的魔数(Magic Number)。

顺便说一句:您的代码很好地使用了浮点类型转换、A 文字和数组 {0} 初始化。

#include <stdio.h>
#include <string.h>

int main(void) {
char string[100];
unsigned count['z' - 'a' + 1] = { 0 };
unsigned accum = 0;

while (scanf("%99s", string) == 1) {
for (int c = 0; string[c]; c++) {
if (string[c] >= 'a' && string[c] <= 'z') {
count[string[c] - 'a']++;
accum++;
} else if (string[c] >= 'A' && string[c] <= 'Z') {
count[string[c] - 'A']++;
accum++;
}
}
}
for (int c = 'a'; c <= 'z'; c++) {
if (count[c - 'a'] != 0)
printf("%c %f\n", c, ((double) count[c - 'a']) / accum);
}
return 0;
}

关于c - 尝试计算字母频率时的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26694200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com