我需要知道多少次" Maria"出现在这个数组中,但是当我运行它时,它表示它出现了51次,而我认为它只有8次
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int g;
int i;
const char * nombres[40] = {"Sandra Marisol","Juan Luis","Perez Luis","Carlitos","Maria","Mariana", "Carlota","Anthony",
"Fernando Jan","Alfonso Roche","Julieta Zacatenco","Maria de los Angeles","Laura Jessica",
"Andrea Maria","Jose Maria","Andres Molina","Aline Derrant","Paquito","Luisa","Ana Maria",
"Caleb","Luis Fernando","Mario Alberto","Paula Monica","Otoniel","Elias Primero","Maurico Enrique",
"Anastasia Maria","Maria Juana","Juana de Arco","Aria Montgomery""Hanna Maria","Magdalena","David Green",
"Florian Drake","Edward Jones","Joakin Broder","Paar","Alicia Torres","Juan Pablo"};
for(i = 0; i>40; i++)
{
printf("%s\n", nombres[40]);
if(nombres[i] == "Maria")
g++;
}
if(g>0){
printf("El nombre de Maria aparece %d veces.", g);
}
else {
printf("El nombre de Maria NO aparece");
}
system("pause");
return 0;
}
答案 0 :(得分:0)
if(nombres[i] == "Maria")
您无法比较这样的字符串。您需要使用strstr()
来查找字符串中的子字符串。
另外,
printf("%s\n", nombres[40]);
可能应该i
而不是40
。而你在for循环中间的比较是倒退的。
而且......可能还有其他错误,但这对我来说已经足够了。
答案 1 :(得分:-2)
有很多错误.....让我们看看我能解决多少...... xd
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int g=0;
int i;
const char * nombres[40] = {"Sandra Marisol","Juan Luis","Perez Luis","Carlitos","Maria","Mariana", "Carlota","Anthony",
"Fernando Jan","Alfonso Roche","Julieta Zacatenco","Maria de los Angeles","Laura Jessica",
"Andrea Maria","Jose Maria","Andres Molina","Aline Derrant","Paquito","Luisa","Ana Maria",
"Caleb","Luis Fernando","Mario Alberto","Paula Monica","Otoniel","Elias Primero","Maurico Enrique",
"Anastasia Maria","Maria Juana","Juana de Arco","Aria Montgomery""Hanna Maria","Magdalena","David Green",
"Florian Drake","Edward Jones","Joakin Broder","Paar","Alicia Torres","Juan Pablo"};
for(i = 0; i<40; i++)
{
printf("%s\n", nombres[i]);
if(!strcmp(nombres[i],"Maria"))
g++;
}
if(g>0){
printf("El nombre de Maria aparece %d veces.", g);
}
else {
printf("El nombre de Maria NO aparece");
}
return 0;
}
此处计数器变量g未初始化。它应该初始化为0 otherwize它包含一些垃圾值。然后在for循环条件错误循环没有被执行,因为你写I> 40这里我被初始化为0所以条件得到假和循环不要run.then循环中的printf包含nombres [40],它给出了一个nullpointer,因为你的姓氏是hombres [39]。然后在if条件下你不能像其他变量一样比较字符串你必须使用lib函数 strcmp 表示字符串比较。 在以下条件
strcmp(s1,s2);
**
*if s1==s2 then it returns 0.
If s1>s2 then it returns 1
If s1<s2 it returns -1
所以我写了!strcmp();
因此,如果字符串匹配,它将返回0和&#39;!&#39;将其转换为1.
希望这有效。尊敬。