我如何加入while循环和if语句的字段

时间:2015-10-18 07:41:39

标签: c

我在while循环和if语句中使用几乎相同的语句或操作,因为它们的条件相反;我可以做些什么来减少相同语句的数量从2比1,我提到的代码片段在下面< / p> 你可以帮助我......

 while(current1!=*head1)
    {
        int new_carpim=(current2->number)(current1->number);
        int updateResult=new_carpim+current3->number;

        if(updateResult==2)
        {
            carry_happend(*head3,current3);

        }

        else
        {
            current3->number=updateResult;
        }

        current1=drive_temp(*head1,temp1,current1);
        current3=drive_temp(*head3,temp3,current3);


    }

    if(current1==*head1)
    {
        int new_carpim=(current2->number)(current1->number);
        int updateResult=new_carpim+current3->number;

        if(updateResult==2)
        {
            carry_happend(*head3,current3);

        }

        else
        {
            current3->number=updateResult;
        }

1 个答案:

答案 0 :(得分:0)

 while(1) //1 = true = (current1==*head or current1!=*head)
    {
        int new_carpim=(current2->number)(current1->number);
        int updateResult=new_carpim+current3->number;

        if(updateResult==2)
        {
            carry_happend(*head3,current3);

        }

        else
        {
            current3->number=updateResult;
        }

        if(current1==*head1){
               break;
        }

        current1=drive_temp(*head1,temp1,current1);
        current3=drive_temp(*head3,temp3,current3);


    }

更一般地说:

while (condition1 || condition2){  //if condition1 || condition2 == true, make sure to break the loop
     if(condition 1)
            //do something for c1
     else if (condition2)
            // do something for c2
     //do something for either c1 or c2
}