c - 在 C 中使用数组(用另一个输入打印一个输入)

标签 c arrays

我试图让自己更清楚地了解这个问题,但我不知道如何提出我的问题。 所以我想创建一个代码,在其中输入 N 张门票和 N 个中奖者。示例:

输入:

5 3 (Here is 5 and a 3, each one a different input)
382
55
44
451
128
1 
4
3

输出:

382
451
44

所以我的代码是这样的:

#include <stdio.h>

int main()
{
    int winners;    
    int n;
    int m;
    char ticketWinners[1000][100], ticket[1000];
    int i;
    int j;
    int max[100];

    scanf("%d", &n); //Input for Number of tickets
    scanf("%d", &m); //Input of the ticket numbers(order) that won

    for(i=0;i<n;i++)
    {
        scanf("%s",&ticket[i]);
        {
            for(j=0; j<m;j++)   
            {
                scanf("%s", &ticketWinnersj]);  
            }

            if (j=i);
                printf("%d", winners);
        }
    }
}

问题是我不知道如何打印票 1、4 和 3。(我可以通过输入选择哪些票赢了。所以不是 1、4 和 3;我可以选择 3、5和 1 个)

最佳答案

如果我正确理解您的问题,则以下内容应该有效。

在原始代码中有一个嵌套循环。我假设这不是本意。

在原始代码中,整数被读入 char 数组。我改成了int,因为这样更符合程序逻辑。

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int winners;
    int n;
    int m;
    int ticketWinners[1000], ticket[1000];
    int i;
    int j;
    int max[100];

    scanf("%d", &n); //Input for Number of tickets
    scanf("%d", &m); //Input of the ticket numbers(order) that won

    for(i = 0; i < n; i++)
    {
        scanf("%d", &ticket[i]);
    }

    for(j = 0; j < m; j++)
    {
        scanf("%d", &ticketWinners[j]);
    }

    for(j = 0; j < m; j++)
    {
        // ticketWinners[] has the index of winners. Lets access
        // ticket[] with those indices. Since input index starts 
        // from 1 rather than 0, subtract 1 
        printf("%d \n", ticket[ticketWinners[j] - 1]);
    }
}

关于c - 在 C 中使用数组(用另一个输入打印一个输入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33159107/

相关文章:

c - 如何将字符串标记输入二维数组?

c - 分配一个未知大小的数组

c++ - 使用 ctypes 将结构传递给 native 库时遇到问题

c++ - 将 c 枚举导入到 c++ 类定义

c# - 通过 C# 对 C 程序的多个输入

java - 显示多个结果数组搜索

java - 为什么java允许零长度索引(在中间)数组?

javascript - 使用高阶函数代替两个循环

c - 指向指针数组的段错误和内存损坏

c - 鉴别 "bit stuffing"之后的位