了解数组和函数

时间:2014-01-28 19:55:47

标签: c arrays

我正在向您显示的程序要求用户输入no。人们问每个人该人吃了多少煎饼。然后它打印出最多的煎饼。 好的,直到现在我发现它很容易做到。 我想做的是(不使用指针)陈述最吃的人。

这是我到目前为止所做的。

#include <stdio.h>

int main()
{
int person, i;
int pancake[50];

printf("Enter Number Of People: ");
scanf("%d", &person);

for (i=1; i<=person; i++)
{
    printf("Person [%d]: ", i);
    scanf("%d",&pancake[i]);
}

for (i=1; i<=person; i++)
  {
    if (pancake[1]<pancake[i])
    {
        pancake[1] = pancake[i];
    }
  }
  printf("Most pancakes eaten is %d\n", pancake[1]);
}

任何想法如何找到或者我是否有必要使用指针?

2 个答案:

答案 0 :(得分:0)

无需使用指针。我发布了完整修改后的 1。代码,因为代码中存在许多错误/拼写错误。

#include <stdio.h>
#include <string.h>
int main(void)
{
    int person, i;
    int pancake[50];

    printf("Enter Number Of People: ");
    scanf("%d", &person);
    char name[person][30];              // 2D array to store the name of persons. Note that I used variable length arrays. 

   for (i=0; i < person; i++)
   {
       printf("Person [%d]: ", i+1);
       scanf("%d",&pancake[i]);
       printf("Person %d name: ", i+1);
       getchar();                       // To eat up the newline left behind by previous scanf.
       fgets(name[i], 30, stdin);       // To read the persons name. I removed the scanf.
   }

   for (i=0; i<person-1; i++)
   {
       if (pancake[0]<pancake[i+1])
       {
           pancake[0] = pancake[i+1];
           strcpy(name[0] , name[i+1]);  // A function in <string.h> to copy strings.
       }
   }
   printf("Most pancakes eaten is %d by %s \n", pancake[0], name[0]);
}  

<子> 1。一些有用的链接:
I. fscanf
II。 getchar
III。 strcpy

答案 1 :(得分:0)

@haccks解决方案的修改版本,它以无效的方式显示了如何在没有指针的情况下执行操作。注意将魔术数字消除到#define,插入的返回值使其编译

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

#declare NUM_PANCAKES 50
#declare NAME_LENGTH_MAX 30

int main(void)
{
    int person, i;
    int pancake[NUM_PANCAKES];
    int best_index = 0;
    int most_pancakes = 0;

    printf( "Enter Number Of People: ");
    scanf( "%d", &person);
    char name[person][NAME_LENGTH_MAX]; /* variable length list... */

    /* get the data */
    for ( i = 0; i < person; i++ )
    {
        printf( "Person [%d]: ", i + 1);
        scanf( "%d", &pancake[i] );
        printf( "Person %d name: ", i + 1 );
        getchar();
        fgets( name[i], NAME_LENGTH_MAX, stdin );
    }

    /* find the answer */
    for ( i = 0; i < person - 1; i++ )
    { 
        if ( pancake[i] > most_pancakes )
        {
            most_pancackes = pancake[i];
            best_index = i;
        }
    }
    printf( "Most pancakes eaten is %d by %s \n", 
           pancake[best_index],
           name[best_index] );

    return 0;
}