请帮忙。我的程序只运行一次while循环:(
我不知道有什么问题。我在python中也编写了同样的程序,在那里它运行得很好。
我是C语言初学者,我使用的是Atmel的AtMega8微处理器。

#define F_CPU 8000000UL

#include <avr/io.h>
#include <util/delay.h>

int main(void) {
    DDRD = 0xFF;
    int world[9];
    int nextworld[9];
    //from 1 to 8
    //some random start values

    world[1] = 1;
    world[2] = 1;
    world[3] = 1;
    world[6] = 1;
    world[7] = 1;
    world[8] = 1;
    for (int i = 0; i < 9; i++) {
        nextworld[i] = world[i];
    }
    int binworld = 0;
    int tiles = 0;
    //=============================
    if (world[1] == 1) {
        binworld = binworld + 128;
    }
    if (world[2] == 1) {
        binworld = binworld + 64;
    }
    if (world[3] == 1) {
        binworld = binworld + 32;
    }
    if (world[4] == 1) {
        binworld = binworld + 16;
    }
    if (world[5] == 1) {
        binworld = binworld + 8;
    }
    if (world[6] == 1) {
        binworld = binworld + 4;
    }
    if (world[7] == 1) {
        binworld = binworld + 2;
    }
    if (world[8] == 1) {
        binworld = binworld + 1;
    }
    PORTD = binworld;
    //================================
    while (1) {
        _delay_ms(100);
        tiles = 0;
        //the live starts

        for (int i = 0; i < 9; i++) {
            tiles = 0;
            for (int xc = -1; xc <= 1; xc++) {
                if (world[i + xc] == 1) {
                    tiles += 1;
                }

                if (world[i] == 1) {
                    tiles = tiles - 1;
                }
            }
            if (world[i] == 1 && tiles == 0) {
                nextworld[i] = 0;
            }
            else if (world[i] == 0 && tiles == 1) {
                nextworld[i] = 1;
            }
            else if (world[i] == 1 && tiles == 2) {
                nextworld[i] = 0;
            }
        }
        //update old world
        for (int i = 0; i < 9; i++) {
            world[i] = nextworld[i];
        }

        //set null
        binworld = 0;
        //convert
        if (world[1] == 1) {
            binworld = binworld + 128;
        }
        if (world[2] == 1) {
            binworld = binworld + 64;
        }
        if (world[3] == 1) {
            binworld = binworld + 32;
        }
        if (world[4] == 1) {
            binworld = binworld + 16;
        }
        if (world[5] == 1) {
            binworld = binworld + 8;
        }
        if (world[6] == 1) {
            binworld = binworld + 4;
        }
        if (world[7] == 1) {
            binworld = binworld + 2;
        }
        if (world[8] == 1) {
            binworld = binworld + 1;
        }

        PORTD = binworld;
    }
}

最佳答案

可能是因为数组索引在第一次迭代时是负数

for (int i=0; i<9;i++)
    {
        tiles = 0;
        for (int xc=-1; xc <= 1; xc++)
        {
            if (world[i+xc]==1) <== HERE, i(0) + xc(-1) == -1

关于c - 为什么我的程序只调用一次while循环? (Atmel C),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45172039/

10-11 21:21