好吧,标题措辞严厉,所以我会在这里详细解释我的问题。
我有一个2D数组,例如:3x4
{{22, 1, 0 , 2}, {6,5,1,33} , {13,42,0,9}}
这个2D数组是从rand() % 100 + 1
函数中随机选择的。
任务:根据用户的输入,我想检查该号码的大小。
假设输入为3,那么数字由x
表示,然后x = 3
我们可以看到,当x = 3
时,输出将为2
。
如果你不明白,我会展示更多的输入:
如果x = 1
,则输出0,如果x = 2
,则输出1,如果x = 4
,则输出5,如果x = 7
,则输出为13,如果x = 11
,输出-1(因为没有)。
所以,我对编程有点新意,我不知道如何解决它。但我想到的是:
步骤1:从用户处获取输入并将其存储在x。
中步骤2:对2D阵列进行排序(在1d阵列中采用2d阵列,然后进行气泡排序)
步骤3:以某种方式检查arr [x-1]是否有效。如果是,输出它。
你们觉得怎么样?这是我的代码,仅用于打印随机2D数组。任何帮助都将受到高度赞赏!
编辑:这是更新的代码,现在我只需要找到x。
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main(void)
{
int m, n = 0, i, j, k = 0, temp; //m = rows, n = cols
int **arr; //Dynamic alloc. for 2D mat.
int *oneDArr;
srand(time(NULL)); //rand new values
printf("Please enter a number:(m) \n");
scanf("%d", &m);
printf("Please enter a number:(n) \n");
scanf("%d", &n);
arr = (int**)malloc(m * sizeof(int*));
for (i = 0; i < m; i++)
arr[i] = (int*)malloc(n * sizeof(int));
printf("The matrix is %d x %d \n", m, n);
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
arr[i][j] = rand() % 100 + 1;
printf("%d ", arr[i][j]);
}
printf("\n");
}
oneDArr = (int*)malloc((m*n) * sizeof(int));
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
oneDArr[k] = arr[i][j];
printf("%d ", oneDArr[k]);
k++;
}
}
printf("\n");
for (i = k - 1; i > 0; i--) {
for (j = 0;j < i; j++) {
if (oneDArr[j] > oneDArr[j + 1])
{
temp = oneDArr[j];
oneDArr[j] = oneDArr[j + 1];
oneDArr[j + 1] = temp;
}
}
}
for (i = 0; i < m*n;i++)
printf("%d ", oneDArr[i]);
getch();
return 0;
}
答案 0 :(得分:1)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
int main(void){
int m, n, i, j, k, x; //m = rows, n = cols
int **arr; //Dynamic alloc. for 2D mat.
int *oneDArr;
int work[101] = {0};//for sort
srand(time(NULL)); //rand new values
printf("Please enter a number:(m) \n");
scanf("%d", &m);
printf("Please enter a number:(n) \n");
scanf("%d", &n);
arr = (int**)malloc(m * sizeof(int*));
for (i = 0; i < m; i++)
arr[i] = (int*)malloc(n * sizeof(int));
printf("The matrix is %d x %d \n", m, n);
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
arr[i][j] = rand() % 100 + 1;//1-100, 0 is not included.
printf("%3d ", arr[i][j]);
++work[ arr[i][j] ];//Existence flag
}
printf("\n");
}
oneDArr = (int*)malloc((m*n) * sizeof(int));
for (i = 1, k = 0; i <= 100; i++){
if(work[i])
oneDArr[k++] = i;
}
printf("input X :\n");
scanf("%d", &x);
if(x > k)
puts("-1");
else
printf("%d\n", oneDArr[x-1]);
//deallocation
getch();
return 0;
}