2015-10-15 73 views
0

我试图让自己更清楚的问题,但我不知道如何问我的问题。 所以我想创建一个代码,我在其中输入N张票和N个赢家。例如:在C中使用数组(用另一个输入打印输入)

输入:

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 )

回答

2

如果我正确理解你的问题,以下应该工作。

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

在原始代码中,整数被读入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]); 
    } 
} 
+1

我认为你对这个问题的解释是正确的(起初解码有点困难)。但几个尼特。为什么'scanf(“%s”)'然后'atoi'而不是直接使用'scanf(“%d”)'?在使用它作为最后'for'循环中'ticket'的索引之前,可能应该对输入进行清理。 – kaylum

+0

你会很好地解释你的解决方案与原来相比有什么不同。 (现在您已经编辑了代码,这样做更有意义。)请注意,在使用结果之前确保每个'scanf()'操作都成功是一个好主意。 –

+0

@kaylum我只是修复它 – knightrider

相关问题