-2

我是 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

我该怎么做呢?

4

2 回答 2

2

如果我正确理解你的问题,你想在处理程序中做不同的事情b1b2并且b3取决于在处理程序中选择的随机值button吗?

在这种情况下,最简单的可能是在全局中创建随机数变量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
    }
}
于 2012-09-12T09:00:48.110 回答
0

您需要使用 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
}

需要注意的一些事项:

  • The break at the end of each case is important. If you omit this, the case falls through into the next case. Though this is sometimes intentional, generally it isn't and results in subtle and difficult to understand bugs.
  • The 'default' label and code is optional. It is however good programming style to have a default case for exceptional circumstances, as something has probably gone wrong and you should deal with it as such.
于 2012-09-12T09:05:28.267 回答