[英]Why this function returns always 0
I have a problem in this function( int populationTotal(villes ville[], int n, char nom[])
), I've created a structure of city have a name and number of poeple and name of his country, and I want from the user to gives me a name of country and I'll give him the total of the poeple in this country. 我在此函数中有问题(
int populationTotal(villes ville[], int n, char nom[])
),我创建了一个城市结构,其名称和人数以及他的国家/地区名称,我想要从用户那里给我一个国家的名字,我会给他这个国家的总人数。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct ville
{
char nom[50];
int population;
char pays[30];
}villes;
void chargement(villes villes[], int n)
{
int i;
for(i=0; i<n; i++)
{
printf("Entrez le nom de la ville n° %d: \n", i+1);
gets(villes[i].nom);
printf("Entrez la population de la ville n° %d:\n", i+1);
scanf("%d", &villes[i].population);
getchar();
printf("Entrez le pays de la ville n° %d:\n", i+1);
gets(villes[i].pays);
}
}
int populationTotal(villes ville[], int n, char nom[])
{
int Total=0, i;
for(i=0; i<n; i++)
{
if(strcmp(ville[i].pays, nom))
Total += ville[i].population;
}
return Total;
}
int main()
{
villes ville[50];
int n;
char pays[30];
printf("Entrez le nombre de villes: \n");
scanf("%d", &n);
getchar();
if( n < 1 || n > 50)
printf("Le nombre doit etre...");
else
{
chargement(ville, n);
printf("Entrez le pays: \n");
gets(pays);
printf("La population total est: %d", populationTotal(ville, n, pays));
}
}
You're not checking the pays
string correctly: 您没有正确检查
pays
字符串:
if(strcmp(ville[i].pays, nom))
The strcmp
function returns 0 if the two strings match and non-zero if they don't match. 如果两个字符串匹配,则
strcmp
函数返回0;如果不匹配,则返回非零。 Since a conditional is considered true if it evaluates to non-zero, the if
portion is only entered when pays
does not match each ville[i].pays
. 由于条件被认为是真实的,如果它的计算结果为非零,则
if
当部分仅输入pays
不匹配每个ville[i].pays
。 And because you entered the same pays
string for each village as well as the separate pays
string, they all match so the if
condition is never entered. 并且由于您为每个村庄输入了相同的
pays
字符串以及单独的pays
字符串,因此它们都匹配,因此永远不会输入if
条件。
If you entered a different pays
for one village then the if
would be entered for that one and you would get a non-zero return value from the function. 如果您为一个村庄输入了不同的
pays
, if
为那个村庄输入if
,您将从函数中获得非零的返回值。
You need to compare the result of strcmp
with 0 to see if the strings match. 您需要将
strcmp
的结果与0进行比较,以查看字符串是否匹配。
if(strcmp(ville[i].pays, nom) == 0)
Also, never use gets
but instead use fgets
. 另外, 从不使用
gets
而是使用fgets
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.