0

我想创建一个二维数组,其中行数和列数是固定的,列值将从控制台输入中获取。

void main() {
    int myArray[3][5];
    int i;
    int a, b, c, d, e; // for taking column values

    for (i = 0; i < 3; i++) { // i represents number of rows in myArray
        printf("Enter five integer values: ");
        // taking 5 integer values from console input
        scanf("%d %d %d %d %d", &a, &b, &c, &d, &e);

        // putting values in myArray
        myArray[i][1] = a;
        myArray[i][2] = b;
        myArray[i][3] = c;
        myArray[i][4] = d;
        myArray[i][5] = e;
    }
    // print array myArray values (this doesn't show the correct output)
    for (i = 0; i < 3; i++) {
        printf("%d\t %d\t %d\t %d\t %d\t", &myArray[i][1], &myArray[i][2],
               &myArray[i][3], &myArray[i][4], &myArray[i][5]);
        printf("\n");
    }
}

当我运行这个程序时,它正确地接受输入,但没有按预期显示数组输出。我怎么能这样做,有什么想法吗?请帮忙。

4

3 回答 3

2

您的第二维从 myArray[i][0] 声明到 myArray[i][4]。它不是从 myArray[i][1] 到 myArray[i][5]

于 2014-09-01T17:51:02.807 回答
1

You had unnecessary & operators in final print. I also removed your a, b, c, d, e variables in order to make the code more concise. You can scanf the values in the arrays directly passing the address of each element.

#include <stdio.h>
void main()
{
    int myArray[3][5];
    int i;

    for(i=0; i<3; i++){ //i represents number of rows in myArray
        printf("Enter five integer values: ");
        //taking 5 integer values from console input
        scanf("%d %d %d %d %d",&myArray[i][0], &myArray[i][1], &myArray[i][2], &myArray[i][3], &myArray[i][4]);  // you can directly scan values in your matrix

    }


    for(i=0; i<3; i++){
        printf("%d\t %d\t %d\t %d\t %d\t\n", myArray[i][0], myArray[i][1], myArray[i][2], myArray[i][3], myArray[i][4]); // no need for the & sign which returns the address of the variable
    }

}
于 2014-09-01T17:53:56.313 回答
0

Try using %1d

#include <stdio.h>

int main(void) 
{
    int i;
    int x[5];

    printf("Enter The Numbers: ");

    for(i = 0; i < 5; i++)
    {
        scanf("%1d", &x[i]);
    }

    for(i = 0; i < 5; i++)
    {
        printf("%d\n", x[i]);
    }

    return 0;
}
于 2014-09-01T17:55:07.343 回答