0%

Objective-C基础入门(决策)

if 语句

1
2
3
4
5
6
7
8
9
10
11
int main (int argc, char * argv[]) { 
@autoreleasepool {
int number;
NSLog (@"Type in your number: ");
scanf ("%i", &number);
if ( number < 0 )
number = -number;
NSLog (@"The absolute value is %i", number);
}
return 0;
}

switch 语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
int main (int argc, char * argv[]) {   
@autoreleasepool {
double value1, value2;
char operator;
Calculator *deskCalc = [[Calculator alloc] init];

NSLog (@"Type in your expression.");
scanf ("%lf %c %lf", &value1, &operator, &value2);
[deskCalc setAccumulator: value1];

switch ( operator ) {
case '+':
[deskCalc add: value2];
break;
case '-':
[deskCalc subtract: value2];
break;
case '*':
[deskCalc multiply: value2];
break;
case '/':
[deskCalc divide: value2];
break;
default:
NSLog (@"Unknown operator.");
break;
}
NSLog (@"%.2f", [deskCalc accumulator]);
}
return 0;
}

Boolean变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main (int argc, char * argv[]) {   
@autoreleasepool {
int p, d, isPrime;

for ( p = 2; p <= 50; ++p ) {
isPrime = 1;
for ( d = 2; d < p; ++d )
if ( p % d == 0 )
isPrime = 0;
if ( isPrime != 0 )
NSLog (@"%i ", p);
}
}
return 0;
}

条件操作符

condition ? expression1 : expression2

特殊扩展
condition ?: expression
如果condition是true,那么value是condition
如果condition是false,那么value是expression