首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将代码与数组和字符串一起使用?

如何将代码与数组和字符串一起使用?
EN

Stack Overflow用户
提问于 2019-04-24 05:38:51
回答 1查看 58关注 0票数 -1

以下是我得到的指示:

  1. 如果命令字为find,则读取另一个整数,并在数据集中搜索该整数。
  2. 如果命令字为print,则打印数组
  3. 任何其他命令字都是错误的。读取<

>d12值时,没有命令字的长度将超过20 print,将从数组中再读取一个整数( k ),以获取值k。如果找到,则打印找到k的位置。(1 =数据值,n=最后一个数据值)。

  1. 如果未找到k,则打印not found。这不是错误。
  2. 如果数据中有多个值k,则仅打印第一个值的位置。

代码语言:javascript
复制
#include <stdio.h>

int main (void) {
   int n;
   scanf ("%d", &n);
   if (n < 1) {
      printf ("Error: one or more values must be provided.\n");
      return 1;
   }

   int x [n];
   int a;
   a = 0;
   while (a < n) {
      scanf ("%d", x [a]);
      a = a + 1;
   }

   int k;
   scanf ("%d", &k);
   int i;
   i = 0;
   while (i <= n-1) {
      if (x[i] == k) {
         break;
      }
      i = i + 1;
   }
   if (i < n) {
      printf ("%d\n", k+1);
   } else {
      printf ("not found\n");
   }

   printf ("Error: invalid command\n");
   return 0;
}

建议的策略:

  1. 读取数组数据后,读取字符串。
  2. 如果字符串为find,则读取整数k并执行搜索。
  3. 如果字符串为print,则不要读取k,只打印数组中的数据。
  4. 如果字符串不是findprint,则处理错误。

G240

EN

回答 1

Stack Overflow用户

发布于 2019-04-24 06:36:13

Shai‘’Tavia,我希望我的回答能帮助你了解如何让你的代码工作。您已经完成了第一部分,但是您需要比较用户给出的命令字符串,然后决定下一步要做什么。

代码语言:javascript
复制
#include <stdio.h>
#include <string.h>

#define ARRAYLENGTH 8

void printArray(int *array, int length)
{
    for (int i = 0; i < length; i++)
        printf("%d ", array[i]);
    printf("\n");
}

void search(int *array, int key)
{
    int flag = 0;

    for (int i = 0; i < ARRAYLENGTH; i++)
    {
        if (array[i] == key && flag == 0)
        {
            printf("found %d at index: %d\n", key, i);
            flag = 1;
        }
    }

    if (flag == 0)
        printf("not found\n");
}

int main(void)
{
    char command[20];
    int indx = 0;
    int array[] = {1, 4, 6, 8, 43, 61, 34, 2};
    int n, flag = 0;

    printf("How many times will we run?");
    scanf("%d", &n);

    if (n < 1)
    {
        printf("Error: one or more values must be provided.\n");
        return 1;
    }

    do
    {
        printf("Enter the command word:");
        scanf("%s", command);

        if (strcmp(command, "find") == 0)
        {
            scanf("%d", &n);
            search(array, n);
        }

        else if (strcmp(command, "print") == 0)
            printArray(array, ARRAYLENGTH);

        else
            printf("Command not found\n");

    } while (--n > 0);

    printf("What is your final interger?");
    scanf("%d", &n);

    search(array, n);

    return 0;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55819780

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档