C 一种将数字转换为其在矩阵上位置的有效方法

C 一种将数字转换为其在矩阵上位置的有效方法,c,C,我想做一个输入系统,允许用户选择一个数字,它将返回选择的位置。 例如: | 0 1 2 --+---------- 0 | 1 2 3 1 | 4 5 6 2 | 7 8 9 在这个矩阵中,如果用户输入是5,它应该返回位置{1,1},如果输入是8,它应该返回{2,1} 我编写了一段代码来尝试这样做,但它并不适用于所有场景: 以下是我用C语言编写的代码: VectorPos RequestInput(char arr[][3]) { ch

我想做一个输入系统,允许用户选择一个数字,它将返回选择的位置。 例如:

     | 0  1  2
   --+----------
   0 | 1  2  3
   1 | 4  5  6
   2 | 7  8  9
在这个矩阵中,如果用户输入是5,它应该返回位置{1,1},如果输入是8,它应该返回{2,1}

我编写了一段代码来尝试这样做,但它并不适用于所有场景:

以下是我用C语言编写的代码:

VectorPos RequestInput(char arr[][3])
{
    char input;
    int converted;
    VectorPos loc;

    while (1)
    {
        printf("Enter number between 1-9: ");
        scanf(" %c", &input);
        if (input < '1' || input > '9')
            printf("Invalid board Location.\n\n");
        else
            break;
    }
    converted = atoi(&input);
    int count = 1;
    int i, k;
    i = k = 0;
    for (k = 0; k < 3 && count++ < converted; k++)
    {
        for (i = 0; i < 3 && count++ < converted; i++);
    }
    loc.col = k;
    loc.row = i;
    return loc;
}
VectorPos请求输入(字符arr[][3])
{
字符输入;
整数转换;
矢量位置;
而(1)
{
printf(“输入1-9之间的数字:”);
scanf(“%c”,&input);
如果(输入<'1'| |输入>'9')
printf(“无效的线路板位置。\n\n”);
其他的
打破
}
转换=atoi(&input);
整数计数=1;
int i,k;
i=k=0;
对于(k=0;k<3&&count++
*VectorPos只是一个在一个变量中返回行和列的结构

我想问你是否知道有什么更好更有效的方法可以做到这一点。
谢谢:)

对于这样的矩形网格,您只需要除法和模运算:

// pos = position in grid from 1..
// w = grid width
// x = output x variable (range 0..w-1)
// y = output y variable (range 0..infinity)
// usage: pos_to_xy(4, 3, &x, &y);
void pos_to_xy(int pos, int w, int *x, int *y) {
  pos -= 1;  // Bring range 1.. to 0..
  *y = pos / w;
  *x = pos % w;
}
例如:

int main() {
    for(int i = 1; i <= 9; i++) {
        int x, y;
        pos_to_xy(i, 3, &x, &y);
        printf("%d: (x %d, y %d)\n", i, x, y);
    }
    return 0;
}

你应该更多地阅读技术(例如……的第一章),并考虑使用@ BaselestalyKyv痒…我根本不明白解析和野牛与这个问题有什么关系?@AKX:问题的第一句提到了输入系统。我不是以英语为母语的人,但对我来说,任何形式的输入都与英语有关parsing@Michael:请在您的问题中提供一些-我们需要
VectorPos
的声明。从开源软件中汲取灵感,例如on,类似于您的需求
1: (x 0, y 0)
2: (x 1, y 0)
3: (x 2, y 0)
4: (x 0, y 1)
5: (x 1, y 1)
6: (x 2, y 1)
7: (x 0, y 2)
8: (x 1, y 2)
9: (x 2, y 2)