【发布时间】:2016-03-09 21:31:59
【问题描述】:
好的,这个错误很奇怪,我不知道发生了什么。 我在 at90usb1286 上运行我的代码。
这是有问题的代码:
uint16_t r = rand();
t1 = r;
px = r%52;
t2 = px;
py = r%28;
t3 = py;
px = px * 6;
t4 = px;
py = py * 8;
t5 = py;
py += 8;
上下文:
t# 变量是我用来调试的临时变量... 它们显示在连接的显示器上。 px 和 py 只是全局 uint16_ts。
错误:
除 t4 之外的所有 t# 变量都显示合理值,但无论 t2 显示什么值,t4 都保持为 0。
为什么!!!?
这几个小时一直在我的脑海里挥之不去! :'(
感谢您的建议! :) 我知道这可能不是使用随机数的好方法:P
(我已经标记了 arduino,因为我怀疑它可能相似)
其余代码: (我也尝试过使用非静态全局变量)
#include "util/cli.h"
#include "drivers/lcd/syscalls.h"
#include "drivers/input/syscalls.h"
#include "drivers/led/syscalls.h"
#include "drivers/scheduler/syscalls.h"
#include <util/delay.h>
static int x = 0, y = 0;
static int px;
static int py; /*Pickup*/
static uint16_t score = 0;
static uint8_t dir; /*0 -> NESW <- 3*/
static uint16_t t1, t2, t3, t4, t5;
void render_thread() {
lcd_clear_screen();
while(1) {
cli();
lcd_display_char_xy(' ', x, y);
if(dir & 0x01)
y -= 8;
if(dir & 0x02)
x += 6;
if(dir & 0x04)
y += 8;
if(dir & 0x08)
x -= 6;
if(x < 0)
x = 0;
if(y < 8)
y = 8;
if(x > 312)
x = 312;
if(y > 232)
y = 232;
lcd_display_char_xy('.', px, py);
lcd_display_char_xy('@', x, y);
/*Display score*/
lcd_display_move(0, 0);
lcd_display_hex(&score, 2);
/*Display test variables*/
lcd_display_move(60, 0);
lcd_display_hex(&t1, 2);
lcd_display_move(100, 0);
lcd_display_hex(&t2, 2);
lcd_display_move(140, 0);
lcd_display_hex(&t3, 2);
lcd_display_move(180, 0);
lcd_display_hex(&t4, 2);
lcd_display_move(220, 0);
lcd_display_hex(&t5, 2);
sei();
_delay_ms(16);
}
}
void game_thread() {
px = 24;
py = 32;
while(1) {
cli();
if(px == x && py == y) {
uint16_t r = rand();
t1 = r;
px = r%52;
t2 = px;
py = r%28;
t3 = py;
px = px * 6;
t4 = px;
py = py * 8;
t5 = py;
py += 8;
score++;
}
sei();
scheduler_switch();
}
}
void user_thread() {
while(1) {
if(switch_north())
dir |= 1;
else
dir &= 0x0E;
if(switch_east())
dir |= 1<<1;
else
dir &= 0x0D;
if(switch_south())
dir |= 1<<2;
else
dir &= 0x0B;
if(switch_west())
dir |= 1<<3;
else
dir &= 0x07;
scheduler_switch();
}
}
void cli_start() {
Task* game_task = scheduler_create_task(game_thread, 128);
scheduler_submit_task(game_task);
Task* render_task = scheduler_create_task(render_thread, 128);
scheduler_submit_task(render_task);
Task* user_task = scheduler_create_task(user_thread, 128);
scheduler_submit_task(user_task);
}
【问题讨论】:
-
那么,基本上你想说
(rand()%52)*6总是0? -
t#变量是如何声明的? -
你能显示完整的代码吗?同时提供所有涉及的值。
-
你打电话给
srand了吗?在您的实现中,未播种的rand可能会产生一个可被52整除的数字。rand返回什么? -
如果未提供要求的信息,则投票结束。