Objective-C中rand()之后的If语句



我是Objective-C和C语言的初学者。

我的代码看起来像:

- (IBAction)button:(id)sender {
    int randomproces = rand() % 3;
    switch (randomproces) {
        case 0:
            //do this
            break;
        case 1:
            //do this
            break;
        case 2:
            //do this
            break;
        default;
            break;
    }
}

现在我想设置另外3个按钮,根据随机情况使它们正确或不正确。

- (IBAction)b1:(id)sender {
    //if case 0 then set it correct
    //else incorrect
}
- (IBAction)b2:(id)sender {
    //if case 1 then set it correct
    //else incorrect
}
// etc

我该怎么做?

如果我正确理解您的问题,您是否希望根据在button的处理程序中选择的随机值,在b1b2b3的处理程序内执行不同的操作?

在这种情况下,最简单的可能是将button中的随机数变量设为全局变量,并将其用于其他三个按钮处理程序:

int randomprocess = -1;
- (IBAction)button:(id)sender {
    randomproces = rand() % 3;
    // Do other stuff if needed
}
- (IBAction)b1:(id)sender {
    if (randomprocess == 0) {
        // Do something
    } else {
        // Do something else
    }
}
- (IBAction)b2:(id)sender {
    if (randomprocess == 1) {
        // Do something
    } else {
        // Do something else
    }
}
- (IBAction)b3:(id)sender {
    if (randomprocess == 2) {
        // Do something
    } else {
        // Do something else
    }
}

您需要使用switch语句,因此

switch (num)
{
    case 1:
        //do code
        break;
    case 2:
        //more code
        break;
    default:
        //num didn't match any of the cases.
        //process as appropriate
}

需要注意的一些事项:

  • 每个案例结尾的中断都很重要。如果您忽略了这一点,则该案例将进入下一个案例。虽然这有时是故意的,但通常不是故意的,会导致微妙而难以理解的错误
  • "默认"标签和代码是可选的。然而,在特殊情况下使用默认情况是一种很好的编程风格,因为可能出现了问题,您应该这样处理

最新更新