将for循环转换为if

时间:2014-02-21 20:18:21

标签: c if-statement for-loop avr

您好。我写了一个将LED向右移动的功能。 我使用for循环,我想将其转换为if语句。

#include <mega8535.h> 
#include <delay.h>   

void main(void) {
    int bits = 0b11111110;  
    int i;              
    int j;              
    PORTA = 0xFF;   
    DDRA = 0xFF;   

    for(j = 0; j < 5; j++) {
        for(i = 0; i < 8; i++) {  
            PORTA = ((bits << i) | (bits >> 8-i));  
            delay_ms(500);                                                      
        }                                                   
        PORTA = 0b11111110;                                  
    }      
    PORTA = 0xFF;                       
}

我该怎么做?

2 个答案:

答案 0 :(得分:1)

要展开for循环,您只需复制并粘贴它的内容,每次都用迭代器的当前值替换它。

所以

for(i=0; i<8; i++)                 
{  
PORTA = ((bits<<i) | (bits >> 8-i));  
delay_ms(500);                                                      
}

会变成

//i=0
PORTA = ((bits<<0) | (bits >> 8-0));  
delay_ms(500);  
//i=1
PORTA = ((bits<<1) | (bits >> 8-1));  
delay_ms(500); 
//i=2
PORTA = ((bits<<2) | (bits >> 8-2));  
delay_ms(500); 
//i=3
PORTA = ((bits<<3) | (bits >> 8-3));  
delay_ms(500); 
//i=4
PORTA = ((bits<<4) | (bits >> 8-4));  
delay_ms(500); 
//i=5
PORTA = ((bits<<5) | (bits >> 8-5));  
delay_ms(500); 
//i=6
PORTA = ((bits<<6) | (bits >> 8-6));  
delay_ms(500); 
//i=7
PORTA = ((bits<<7) | (bits >> 8-7));  
delay_ms(500); 

例如,在VHDL中,for循环被转换为等效的展开循环。

答案 1 :(得分:0)

试试这个

    if(i==0){
    PORTA = ((bits<<0) | (bits >> 8));  
    delay_ms(500);
    i++;
    }
    if(i==1){
    PORTA = ((bits<<1) | (bits >> 8-1));  
    delay_ms(500);
    i++;
    }
    if(i==2){
    PORTA = ((bits<<2) | (bits >> 8-2));  
    delay_ms(500);
    i++}
    .
    .
    //so on up to i=7