簡體   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