gpt4 book ai didi

c - C 计数空间中的无限循环

转载 作者:行者123 更新时间:2023-11-30 19:14:54 26 4
gpt4 key购买 nike

我正在编写一个程序来计算空格和元音,但它不起作用,我想我做了一个无限循环。我将向您展示我的代码:

int contar_p(char a[100]) {
int i = 0, spaces = 1;

while (a[i] != '\0' && i < 100) {
if (a[i] == ' ') {
spaces += 1;
i++;
}

}
return spaces;
}

int contar_v(char b[100]) {
int i = 0, counter = 0;

while (b[i] != '\0' && i < 100) {
if (b[i] == 'a' || b[i] == 'e' || b[i] == 'i' || b[i] == 'o' || b[i] == 'u') {
counter += 1;
}
i++;
}
return counter;
}

int main(void){
char phrase[100];
int words = 0, vowels = 0;

printf("write a phrase ");
gets(phrase);

palabras = contar_p(phrase);
vocales = contar_v(phrase);

printf("%d\n", words);
printf("%d", vowels);

return 0;
}

最佳答案

循环

while (a[i]!='\0'&&i<100){
if(a[i]==' '){
spaces+=1;
i++;
}
}

是一个无限循环。将 i++ 放在 if 之外。将其更改为

while (a[i]!='\0'){  // No need of condition i < 100
if(a[i]==' '){
spaces+=1;
}
i++;
}

关于c - C 计数空间中的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33443101/

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