为什么IF语句被侵犯,而输出结果明确表示应该执行?

时间:2018-04-10 01:40:58

标签: c pointers if-statement simulink s-function

上下文:我正在使用Matlab / Simulink模拟我需要follow a reference的电路。为了简化它:低于参考电流然后施加更多电流,高于参考电流然后施加更少的电流。要实现这一点,我必须控制two devices(Sa和Sb),它基本上关闭在我的代码中应用1并打开0(两者同时)。

现在,我有these results,其中重要的图形是S1 Current,S-Function / 2和S-Function / 1以及最后一个问题:考虑到以下代码,为什么会出现S-Function / 2,这是THY [],保持在1而显然有时间段S-Function / 1,这是IGBT [],是0?

  • 下一个代码位于我在Simulink中使用的S-Function中。 This is the entire code

    for (i=0; i<width; i++){
    if (*Is[i] <  *Iref[i]){
        //IGBT[] is S-Function/1 and THY[] is S-Function/2
        //Is[] is S1 Current and Iref[] is Reference Current 1
        IGBT[i] = 1.0;
    
        if ( IGBT[i] == 0.0){
        THY[i] = 0.0;   
        }
        else {
        THY[i] = 1.0; 
        }
        }
        else {
        IGBT[i] = 0.0;   
        }
    }
    

2 个答案:

答案 0 :(得分:0)

看看你的代码:

IGBT[i] = 1.0;

if ( IGBT[i] == 0.0) {
    THY[i] = 0.0;         // <--- will never be executed
}
else {
    THY[i] = 1.0; 
}

假设它按顺序执行(即没有线程),你总是IGBT[i]设置为1,然后else部分将是执行导致THY[i]等于1,因此始终保持1

答案 1 :(得分:0)

我不确定,但我认为代码中存在问题:

for (i=0; i<width; i++){
if (*Is[i] <  *Iref[i]){
    //IGBT[] is S-Function/1 and THY[] is S-Function/2
    //Is[] is S1 Current and Iref[] is Reference Current 1
    IGBT[i] = 1.0;

    if ( IGBT[i] == 0.0){ // condition 1
    // if condition 1 is true then execute this
    THY[i] = 0.0;   
    }
    else {
    // if condition 1 is false then execute this
    THY[i] = 1.0; 
    }
    }
    else {
   // this condition will never be executed
    IGBT[i] = 0.0;   
    }
}

现在,如果条件1为真,那么THY[I] = 0.0;将被执行,如果条件为假则为THY[i] = 1.0;。在你的代码中

 else {
    IGBT[i] = 0.0;   
    }

是一种死代码,永远不会被执行。您需要将else后跟if条件替换为else if(condition),以便其他第二个条件可以执行。

还有一件事

IGBT[i] = 1.0; // IGBT[i] is updated

        if ( IGBT[i] == 0.0){ // IGBT[i]  is compared ... wow

我建议你阅读有关float和double之间的比较。