繁体   English   中英

在Objective-c中的switch案例中的if语句

[英]If statement inside a switch case in Objective-c

我知道在堆栈溢出时有几个类似的问题,但问题是它不能解决我的答案。

我想在开关盒中显示一个if语句。

这是我的代码

 NSMutableArray *stdMarks = [[NSMutableArray alloc]initWithObjects:@"100", @"70", @"97", @"11", @"59", nil];

    int marksObtained;

    for (int i= 0; i < [stdMarks count]; i++) {
        marksObtained += [[stdMarks objectAtIndex:i] integerValue];
    }

    int totalMarks = 500;
    int percentage = (marksObtained * 100)/totalMarks;

    NSLog(@"The total marks are: %d", marksObtained);
    NSLog(@"The percentage is: %d", percentage);
    NSLog(@"The total numbers of subjects are: %d", [stdMarks count]);


    switch (percentage) {
        case 1:
            if (percentage >= 70) {
                NSLog(@"You get 50 percent fee concession");
            }
            break;
        case 2:
            if (percentage >= 60) {
                NSLog(@"You get 45 percent fee concession");
            }
            break;
        default:
            NSLog(@"you do not qualify");
            break;
    }

不管百分比是多少,我都会始终得到默认答案“您不符合条件”。

我究竟做错了什么

请在这里帮我

那是因为给开关提供的percentage只能满足1%和2%,所以这些if语句将永远不会触发,因为要进入这些情况,它们必须低于if语句中的值

我的建议是删除switch语句,因为它似乎不必要,所以只要if / else语句包含所需的范围即可

在您的代码中,如果您的百分比不等于运行1或2,它将变为默认值。

switch (percentage) { <---- this percentage, you only provide the case of 1 and 2.
        case 1:
            if (percentage >= 70) {
                NSLog(@"You get 50 percent fee concession");
            }
            break;
        case 2:
            if (percentage >= 60) {
                NSLog(@"You get 45 percent fee concession");
            }
            break;
        default:
            NSLog(@"you do not qualify");
            break;
    }

猜测您需要更改switch(percentage)中的百分比。

更新:

if (percentage >= 70) {
    NSLog(@"You get 50 percent fee concession");
}
else if (percentage >= 60) {
    NSLog(@"You get 45 percent fee concession");
}
else{
    NSLog(@"you do not qualify");
}

更新:如果要使用开关盒:百分比> = 70

switch (percentage)
case 70:
case 71:
case 72:
case 73:
.
.
.
case 100:
NSLog(@"You get 50 percent fee concession");
break;
case 60:
.
.
.

等等,这是非常愚蠢的,所以如果是其他情况更合适

暂无
暂无

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

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