错误的逻辑?程序并不像我想要的那样工作

时间:2014-07-12 00:11:09

标签: c c89

我正在使用C89

我正在为练习编写一个小程序,我认为我使用的逻辑是正确的,但它打印的结果与我想要的不同。

我的计划如下:

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

struct animal 
{   
    char species[30]; 
    char breed[30];   };

void addAnimal( struct animal unique[], int *count, char* newspecies, char* newbreed);

int main(void)
{

   struct animal unique[10] = { {"Cat", "Persian"}, {"Dog", "Collie"},
                                {"Bird", "Conure"}, {"Dog", "Lab"} };
   int i;
   int count = 4;

   addAnimal(unique, &count, "Cat", "Calico");
   addAnimal(unique, &count, "Bird", "Budgie");
   addAnimal(unique, &count, "Dog", "Lab");

   for( i = 0; i < count+1; i++)
       printf("%s, %s\n", unique[i].species, unique[i].breed);
}

我有这个功能:

void addAnimal( struct animal unique[], int *count, char* newspecies, char* newbreed)
{

    int i, k = 0;
    k = *count;

    for( i = 0; i < k; i ++)
    {
       if( strcmp(unique[i].species, newspecies) && strcmp(unique[i].breed, newbreed) )
       {
          printf("both match\n");
          /* do nothing */
       }
       else
       {
          *count = *count + 1;
          strcpy(unique[*count]. species, newspecies);
          strcpy(unique[*count]. breed, newbreed);
       }
    }
}

基本上我希望函数添加给定的名称(如果它们不存在),并且什么也不做它们确实存在。

我一直得到的(没有所有额外的印刷声明)是

Cat, Persian
Dog, Collie
Bird, Conure
Dog, Lab
, 
Cat, Calico
Bird, Budgie
Dog, Lab

这是错误的。而我也不知道为什么这个逗号正在打印。

2 个答案:

答案 0 :(得分:2)

更改为

void addAnimal( struct animal unique[], int *count, char* newspecies, char* newbreed){
    int i, k = *count;

    for( i = 0; i < k; i++){
       if( strcmp(unique[i].species, newspecies)==0 && strcmp(unique[i].breed, newbreed)==0 ){
          printf("both match\n");
          return ;
       }
    }
    //added only once (Rather than if it does not match the data for each)
    strcpy(unique[*count].species, newspecies);
    strcpy(unique[*count].breed, newbreed);
    *count = *count + 1;
}

并在主

   for( i = 0; i < count; i++)
       printf("%s, %s\n", unique[i].species, unique[i].breed);

答案 1 :(得分:0)

按以下方式定义功能

void addAnimal( struct animal unique[], int *count, const char *newspecies, const char *newbreed);

void addAnimal( struct animal unique[], int *count, const char *newspecies, const char *newbreed)
{
    int i = 0;

    while ( i < *count && 
            ( strcmp( unique[i].species, newspecies ) || strcmp( unique[i].breed, newbreed ) ) i++; 

    if ( i == *count )
    {
          strcpy( unique[*count].species, newspecies );
          strcpy( unique[*count].breed, newbreed );
          ++*count;
    }
    else
    {
          printf( "both match\n" );
    }
}

以下列方式改变主循环

   for ( i = 0; i < count; i++ )
       printf( "%s, %s\n", unique[i].species, unique[i].breed );