C 程序需要帮助修复我的代码(数组的概念)

标签 c

Possible Duplicate:
C programming: Occupying Cells
C programming typing out a list that's modded out by 10

我已经在这个代码上工作了一个星期,但还没有取得任何成功。该程序应该要求用户输入多个单元格。然后提示用户他/她想要占用哪个小区。然后程序会输入一个“?”在指定的占用单元格下方。我只能使用基础知识,所以没有任何我不应该知道的技巧或复杂的东西。

我的程序的问题是,当用户输入 5 和 9 被占用时,它只会打印“???????????????????????????” 。例如,假设我要输入 10 个单元格,并希望 5 和 9 被占用,那么屏幕应如下所示:

0123456789
     ?   ?

这是我的完整作品:

# include <stdio.h>
# define LENGTH 80

void display(int data[], int length);

int main()
{
    int input=0,i;
    int data[80];
    int index = 0;
    char occupied = '?';
    int cells,j,time;

    printf("Enter the number of cells:");
    scanf("%d", &cells);
    printf("Enter the number of cells you want occupied. The maximum number is 80. Type -1 to stop.:");
    scanf("%d", &input);
    printf("The original index is: %d",index);
    printf("\n");
    data[index] = input;
    index++;
    printf("The new index is: %d", index);
    printf("\n");

    for(i = 0; i < cells; i++) {
        printf("%d", i%10);
    }
    display(data, LENGTH);

}

void display(int data[], int length)
{
    int input=0,i;
    int index = 0;
    int cells,time;
    char occupied;


    if(input!=-1 && input <= 80) {
        data[index] = 1;
        occupied = '?';
        (char) data[index] = occupied;
    }
    else {
        data[index] = 0;
        occupied = ' ';
        (char) data[index] = occupied;
    }

    printf("\n");

    for(i = 0; i < length; i++){
        printf("%c", data[index]);
    }
}

关于索引的 printf 和 scanf 行对我来说实际上只是一个健全性检查。

最佳答案

这里有很多错误。首先,您可以在一个实例中 scanf 一个数组。使用循环。其次,您错误地调用了 display() 。使用单元格,而不是长度。我这里有一个有效的代码。

# include <stdio.h>

int main()
{
    int input=0,i;
    char data[80];
    int cells;
    int occupyMax = 0;
    int n = 0;

    printf("Enter the number of cells:");
    scanf("%d", &cells);

    printf("Enter number of cells you want occupied. The maximum number is 80:");
    scanf("%d", &occupyMax);

    // Ensure that # of occupied cells is lesser than max.
    if (occupyMax> cells)
    {
        printf("Error!");
        return;
    }

    // Init data to blank cells.
    for(i=0;i<80;i++)
    {
        data[i]=' ';
    }

    for( n = 0; n < occupyMax; n++) 
    {
        printf("Enter occupy cell number(Numbering starts at 0)\n");
        scanf("%d", &input );
        data[input] = '?';
    }

    // Display
    for(i = 0; i < cells; i++) 
    {
        printf("%d", i%10);
    }
    printf("\n");
    for(i = 0; i < cells; i++) 
    {
        printf("%c", data[i]);
    }
}

关于C 程序需要帮助修复我的代码(数组的概念),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8100504/

相关文章:

c - 为什么我的函数按升序而不是最小堆对元素进行排序?

C 和加法,先整数后后

c - 二维数组中的第一个元素被覆盖 - C

捕捉 WM_DEVICECHANGE

c - 在 C 中查找 malloc() 数组长度?

c - 如何在C中打印二进制数据?

c - 如何在空 vector 中传递值?

c - 在 C 中分配矩阵

c - 如何在 Linux 内核模块中分配可执行页面?

c++ - 多线程交换 2 个预定义指针到 1 个静态指针线程安全吗?