簡體   English   中英

C,用for循環初始化2D數組

[英]C, Initialize 2D array with a for loop

我在用值填充2d數組時遇到問題。 很多示例都有一個靜態數組,但是,我使用的是for循環來填充它。 這是我希望我的代碼執行的操作:

  • 第二個參數是d,假設用戶輸入3,則:
  • 創建一個3x3數組。
  • 該數組將存儲從8到0的所有值。
  • 它將這樣的數組打印到終端:

8 7 6

5 4 3

2 1 0

  • 如果用戶輸入4,則將創建4x4數組
  • 它將打印到控制台:

15 14 13 12

11 10 9 8

7 6 5 4

3 2 1 0

/**
 * fifteen.c
 *
 * Computer Science 50
 * Problem Set 3
 *
 * Implements the Game of Fifteen (generalized to d x d).
 *
 * Usage: ./fifteen d
 *
 * whereby the board's dimensions are to be d x d,
 * where d must be in [MIN,MAX]
 *
 * Note that usleep is obsolete, but it offers more granularity than
 * sleep and is simpler to use than nanosleep; `man usleep` for more.
 */

#define _XOPEN_SOURCE 500

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

// board's minimal dimension
#define MIN 3

// board's maximal dimension
#define MAX 9

// board, whereby board[i][j] represents row i and column j
int board[MAX][MAX];

// board's dimension
int d;

// prototypes
void clear(void);
void greet(void);
void init(void);
void draw(void);
bool move(int tile);
bool won(void);
void save(void);

int main(int argc, string argv[])
{
    // greet player
    greet();

    // ensure proper usage
    if (argc != 2)
    {
        printf("Usage: ./fifteen [3-9]\n");
        return 1;
    }

    // ensure valid dimensions
    d = atoi(argv[1]);
    if (d < MIN || d > MAX)
    {
        printf("Board must be between %i x %i and %i x %i, inclusive.\n",
            MIN, MIN, MAX, MAX);
        return 2;
    }

    // initialize the board
    init();

    // accept moves until game is won
    while (true)
    {
        // clear the screen
        //clear();

        // draw the current state of the board
        draw();

        // saves the current state of the board (for testing)
        save();

        // check for win
        if (won())
        {
            printf("ftw!\n");
            break;
        }

        // prompt for move
        printf("Tile to move: ");
        int tile = GetInt();

        // move if possible, else report illegality
        if (!move(tile))
        {
            printf("\nIllegal move.\n");
            usleep(500000);
        }

        // sleep for animation's sake
        usleep(500000);
    }

    // that's all folks
    return 0;
}

/**
 * Clears screen using ANSI escape sequences.
 */
void clear(void)
{
    printf("\033[2J");
    printf("\033[%d;%dH", 0, 0);
}

/**
 * Greets player.
 */
void greet(void)
{
    clear();
    printf("GAME OF FIFTEEN\n");
    //usleep(2000000);
}

/**
 * Initializes the game's board with tiles numbered 1 through d*d - 1,
 * (i.e., fills board with values but does not actually print them),
 * whereby board[i][j] represents row i and column j.
 */
void init(void)
{
    // TODO
    // represent board in 2D integer array
    // int board [MAX][MAX]
    // int d
    // size of board. d <= MAX
    // board [i][j] represents the element at row i and col j
    // starts in descending order
    // if number of tiles is odd, swap 2 and 1

    /**
    take d and print board with dxd dimensions
    loop through x to go up to d-1 (i.e. 4x4 board = 16, values will be 15 to 1)
    */

    //initialize array
    int numbers[d][d];

    //print the array size
    printf("Array size:%d\n", d);

    //variable i, j
    int i;
    int j;

    // board's numbering
    int s = (d*2)-1;
    int countarray[d];
    int count;
    for (count = s; count > 0; count--)
    {
        countarray[count]=count;
    }
    printf("Start of board's numbering: %d\n", s);

    //assign values to array with loop

        for (i = 0; i < d; i++)
        {
                for ( j = 0; j < d; j++)
                {
                    numbers[i][j] = 0;
                    numbers[i][j] = countarray[count];
                    printf("numbers[%d][%d] = %d \n", i, j, numbers[i][j]);
                }
        }

     //print a number from the array
    printf("The 4th integer of the array is: %d\n", numbers[3][3]);
    printf("Value of d: %d\n", d);
    for (int x = 0; x < d; x++){
        for (int y = 0; y < d; y++){
            // print the array value [ x, y ]
            printf("%d", numbers[x][y]);
            printf(" ");
        }
        // print a new line here
        printf("\n");
    }
}

/**
 * Prints the board in its current state.
 */
void draw(void)
{
    // TODO
    // print current state of the board
    // print a blank space fore single digit #s
    // printf("%2d", board[i][j]);

    /**
    for each row
        for each value in row
            print value and space
        print new line
    */


}

/**
 * If tile borders empty space, moves tile and returns true, else
 * returns false. 
 */
bool move(int tile)
{
    // TODO
    return false;
}

/**
 * Returns true if game is won (i.e., board is in winning configuration), 
 * else false.
 */
bool won(void)
{
    // TODO
    return false;
}

/**
 * Saves the current state of the board to disk (for testing).
 */
void save(void)
{
    // log
    const string log = "log.txt";

    // delete existing log, if any, before first save
    static bool saved = false;
    if (!saved)
    {
        unlink(log);
        saved = true;
    }

    // open log
    FILE* p = fopen(log, "a");
    if (p == NULL)
    {
        return;
    }

    // log board
    fprintf(p, "{");
    for (int i = 0; i < d; i++)
    {
        fprintf(p, "{");
        for (int j = 0; j < d; j++)
        {
            fprintf(p, "%i", board[i][j]);
            if (j < d - 1)
            {
                fprintf(p, ",");
            }
        }
        fprintf(p, "}");
        if (i < d - 1)
        {
            fprintf(p, ",");
        }
    }
    fprintf(p, "}\n");

    // close log
    fclose(p);
}

參數為3時,它將正確地將3x3數組打印到終端。 但是,數組中的所有9個值均為134517847。感謝您的幫助。

在內部循環中,錯誤的變量x被遞增。 應該是y ++,而不是x ++。

 for (int x = 0; x < d; x++){
    for (int y = 0; y < d; x++){
                           ^^^

循環需要迭代count ==0。將條件從>更改為> =。

    for (count = s; count >= 0; count--)
    {
        countarray[count]=count;
    }

s初始化為

  int s = (d*2)-1;

但這不是d * d-1嗎?

  int s = (d*d)-1;

在初始化數字數組的循環中,未初始化計數也未減少計數。 我猜你需要這樣的東西:

count = s;
for (i = 0; i < d; i++)
{
        for ( j = 0; j < d; j++)
        {
            numbers[i][j] = countarray[count--];
            printf("numbers[%d][%d] = %d \n", i, j, numbers[i][j]);
        }
}

此外,你的循環為y增量x ,你是不是在數組中的值設置為任何有意義的事。

numbers[i][j] = countarray[count];

count在此循環內從未真正改變過。 您應該要么循環到最大值,然后數學計算出行和列,要么將變量分配給最大值,然后在分配給數組時遞減。

最簡單的方法是將二維數組視為常規數組

init(d, &board[0][0]);

init()函數

void init(int d, int *array) {
    int dd = d * d;
    do *array++ = --dd; while (dd > 0);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM