简体   繁体   English

如何减少 c 中的相同 if-else

[英]how can I reduce same if-else in c

Hi I am making a math quiz program with arduino and when I was coding, I had a problem.嗨,我正在用 arduino 制作一个数学测验程序,当我编码时,我遇到了问题。 There should be a lot of if-else and switch-case for the quiz program.测验程序应该有很多 if-else 和 switch-case。 It would be nice if you let me know how to reduce these codes.如果您让我知道如何减少这些代码,那就太好了。 I am not really good at coding so it would also be nice if you could send me an actual reduced code:) I am trying to make 30 questions and the code I posted is for only 3 questions.. Thanks a lot!!我不太擅长编码,所以如果你能给我发送一个实际的简化代码也很好:)我正在尝试提出 30 个问题,而我发布的代码只针对 3 个问题。非常感谢!

    switch (screen) {
        case 0: // welcome
            if (buttonState1 && buttonState2) {
                screen = 1;
                delay(50);
            }

            break;

        case 1: // question one
            if(buttonState1 && userAnswerOne == ""){ //store users answer
            userAnswerOne = "True";
               if(userAnswerOne == questionOneAnswer){ //check to see if answer is correct
                score = score + 1;  
                digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)
                delay(1000);
                digitalWrite(7, LOW);    // turn the LED off by making the voltage LOW
                delay(1000);                       // wait for a second
                screen = 2;  
                delay(50);                     
             }
               else{
                  digitalWrite(10, HIGH);   // turn the LED on (HIGH is the voltage level)
                  delay(1000);                       // wait for a second
                  digitalWrite(10, LOW);    // turn the LED off by making the voltage LOW
                  delay(1000);        
                screen = 2;
                delay(50);                
              }
            }
            if(buttonState2 && userAnswerOne == ""){
            userAnswerOne = "False";
               if(userAnswerOne == questionOneAnswer){ //check to see if answer is correct
                digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)
                delay(1000);
                digitalWrite(7, LOW);    // turn the LED off by making the voltage LOW
                delay(1000);                       // wait for a second
                score = score + 1;  
                screen = 2;  
                delay(50);  
             }
               else{
                  digitalWrite(10, HIGH);   // turn the LED on (HIGH is the voltage level)
                  delay(1000);                       // wait for a second
                  digitalWrite(10, LOW);    // turn the LED off by making the voltage LOW
                  delay(1000);        
                screen = 2;
                delay(50);
              }
            }
            break;

        case 2: // question two
            if(buttonState1 && userAnswerTwo == ""){ //store users answer
            userAnswerTwo = "True";
               if(userAnswerTwo == questionTwoAnswer){ //check to see if answer is correct
                digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)
                delay(1000);
                digitalWrite(7, LOW);    // turn the LED off by making the voltage LOW
                delay(1000);                       // wait for a second
                score = score + 1;  
                screen = 3;  
                delay(50);                     
             }
               else{
                  digitalWrite(10, HIGH);   // turn the LED on (HIGH is the voltage level)
                  delay(1000);                       // wait for a second
                  digitalWrite(10, LOW);    // turn the LED off by making the voltage LOW
                  delay(1000);                       // wait for a second
                screen = 3;
                delay(50);                
              }
            }
            if(buttonState2 && userAnswerTwo == ""){
            userAnswerTwo = "False";
               if(userAnswerTwo == questionTwoAnswer){ //check to see if answer is correct
                digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)
                delay(1000);
                digitalWrite(7, LOW);    // turn the LED off by making the voltage LOW
                delay(1000);                       // wait for a second
                score = score + 1;  
                screen = 3;  
                delay(50);  
             }
               else{
                  digitalWrite(10, HIGH);   // turn the LED on (HIGH is the voltage level)
                  delay(1000);                       // wait for a second
                  digitalWrite(10, LOW);    // turn the LED off by making the voltage LOW
                  delay(1000); 
                screen = 3;
                delay(50);
              }
            }
            break;  

        case 3: // question three
            if(buttonState1 && userAnswerThree == ""){ //store users answer
            userAnswerThree = "True";
               if(userAnswerThree == questionThreeAnswer){ //check to see if answer is correct
                digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)
                delay(1000);
                digitalWrite(7, LOW);    // turn the LED off by making the voltage LOW
                delay(1000);                       // wait for a second
                score = score + 1;  
                screen = 4;  
                delay(50);                     
             }
               else{
                  digitalWrite(10, HIGH);   // turn the LED on (HIGH is the voltage level)
                  delay(1000);                       // wait for a second
                  digitalWrite(10, LOW);    // turn the LED off by making the voltage LOW
                  delay(1000); 
                screen = 4;
                delay(50);                
              }
            }
            if(buttonState2 && userAnswerThree == ""){
            userAnswerThree = "False";
               if(userAnswerThree == questionThreeAnswer){ //check to see if answer is correct
                digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)
                delay(1000);
                digitalWrite(7, LOW);    // turn the LED off by making the voltage LOW
                delay(1000);                       // wait for a second
                score = score + 1;  
                screen = 4;  
                delay(50);  
             }
               else{
                  digitalWrite(10, HIGH);   // turn the LED on (HIGH is the voltage level)
                  delay(1000);                       // wait for a second
                  digitalWrite(10, LOW);    // turn the LED off by making the voltage LOW
                  delay(1000);        
                screen = 4;
                delay(50);
              }
            }
            break;  

Not the answer to your question but you have another problem here:不是您问题的答案,但您在这里还有另一个问题:

userAnswerOne == ""

It is a bug.这是一个错误。 It will not work as you compare the pointer to the address of the string literal "" .当您将指针与字符串文字""地址进行比较时,它将不起作用。 It does not compare the strings or does not check if the string is empty.比较字符串或检查字符串是否为空。

You need to:你需要:

!strcmp(userAnswerOne ,"")

or或者

!userAnswerOne[0]

I had to make some assumptions about variable definitions, etc.我不得不对变量定义等做出一些假设。

These examples have been coded, but not compiled or tested.这些示例已编码,但未编译或测试。

Whenever I see (eg) int v1, v2, v3, ..., vN;每当我看到(例如) int v1, v2, v3, ..., vN; , I refactor to an array: int v[N]; ,我重构为一个数组: int v[N];

Your string comparisons are incorrect [and won't even compile cleanly].您的字符串比较不正确 [甚至无法干净地编译]。 To compare strings, use strcmp .要比较字符串,请使用strcmp

There is much replicated code that can be moved to [new] functions有很多复制代码可以移动到 [新] 函数


Here's a first cut that eliminates replicated code but keeps the switch :这是消除复制代码但保留switch的第一个剪辑:

int screen;

int button[2];
const char *userans[4];
const char *questans[4];

// cmpeq -- compare two strings for equality
int
cmpeq(const char *lhs,const char *rhs)
{

    return (strcmp(lhs,rhs) == 0);
}

// ifstate -- check for button press and expected user answer
int
ifstate(int butno,int ansno,const char *ansexp)
{

    return button[butno] && cmpeq(userans[ansno],ansexp));
}

// dopulse -- pulse the led
void
dopulse(int ledno)
{

    // turn the LED on (HIGH is the voltage level)
    digitalWrite(ledno, HIGH);
    delay(1000);

    // turn the LED off by making the voltage LOW
    digitalWrite(ledno, LOW);

    // wait for a second
    delay(1000);
}

void
newstate(void)
{
    int cmpflg;

    switch (screen) {
    case 0:  // welcome
        if (button[1] && button[2]) {
            screen = 1;
            delay(50);
        }
        break;

    case 1:  // question one
        // store users answer
        if (ifstate(1,1,"")) {
            userans[1] = "True";

            cmpflg = cmpeq(userans[1],questans[1]);
            score += cmpflg;
            dopulse(cmpflg ? 7 : 10);
            delay(50);

            screen = 2;
        }

        if (ifstate(2,1,"")) {
            userans[1] = "False";

            cmpflg = cmpeq(userans[1],questans[1]);
            score += cmpflg;
            dopulse(cmpflg ? 7 : 10);
            delay(50);

            screen = 2;
        }
        break;

    case 2:  // question two
        if (ifstate(1,2,"")) {
            userans[2] = "True";

            cmpflg = cmpeq(userans[2],questans[2]);
            score += cmpflg;
            dopulse(cmpflg ? 7 : 10);
            delay(50);

            screen = 3;
        }

        if (ifstate(2,2,"")) {
            userans[2] = "False";

            cmpflg = cmpeq(userans[2],questans[2]);
            score += cmpflg;
            dopulse(cmpflg ? 7 : 10);
            delay(50);

            screen = 3;
        }
        break;

    case 3:  // question three
        if (ifstate(1,3,"")) {
            userans[3] = "True";

            cmpflg = cmpeq(userans[3],questans[3]);
            score += cmpflg;
            dopulse(cmpflg ? 7 : 10);
            delay(50);

            screen = 4;
        }

        if (ifstate(2,3,"")) {
            userans[3] = "False";

            cmpflg = cmpeq(userans[3],questans[3]);
            score += cmpflg;
            dopulse(cmpflg ? 7 : 10);
            delay(50);

            screen = 4;
        }
        break;
    }
}

int
main(void)
{

    while (1)
        newstate();

    return 0;
}

Here's a version that eliminates the switch and just increments screen .这是一个消除switch并仅增加screen的版本。 It can handle an arbitrary number of questions:它可以处理任意数量的问题:

int screen;                         // current question number

int button[2];                      // button press staet

#define NQUEST      20
const char *userans[NQUEST];        // user answers
const char *questans[NQUEST];       // correct answers to questions

// cmpeq -- compare two strings for equality
int
cmpeq(const char *lhs,const char *rhs)
{

    return (strcmp(lhs,rhs) == 0);
}

// dopulse -- pulse the led
void
dopulse(int ledno)
{

    // turn the LED on (HIGH is the voltage level)
    digitalWrite(ledno, HIGH);
    delay(1000);

    // turn the LED off by making the voltage LOW
    digitalWrite(ledno, LOW);

    // wait for a second
    delay(1000);
}

// dotest -- test answer
int
dotest(void)
{
    int press;

    do {
        press = (button[1] || button[2]);

        // user has not pressed any button
        if (! press)
            break;

        // user has pressed true or false
        int truebut = button[1];
        if (truebut)
            userans[screen] = "True";
        else
            userans[screen] = "False";

        int cmpflg = cmpeq(userans[screen],questans[screen]);
        score += cmpflg;

        dopulse(cmpflg ? 7 : 10);
        delay(50);

        screen += 1;
    } while (0);

    return press;
}

// wait for user to _release_ buttons
void
wait_buttons_up(void)
{
    while (button[1] || button[2]) {
        // update button state [by reading port if necessary ...
    }
}

int
main(void)
{

    // fill in correct answers ...
    for (screen = 1;  screen <= NQUEST;  ++screen)
        questans[screen] = "False";
    questans[3] = "True";
    questans[7] = "True";
    questans[11] = "True";
    // ...

    // welcome -- wait for _both_ buttons to be pressed
    while (1) {
        if (button[1] && button[2]) {
            screen = 1;
            delay(50);
            break;
        }
    }

    wait_buttons_up();

    screen = 1;
    while (1) {
        if (dotest())
            wait_buttons_up();
    }

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM