我的学习日志008:第一个程序“分歧解决器”
交代一下我做程序的工具:mac os x虚拟机10.9.3 Xcode6 百度^-^ 参考书iPhone30天精通
程序功能简介:做一个随机得到结果的程序,一个label显示,4个button,每点一下button都会在label上显示一个结果,结果是在一定范围呢随机产生的。
.h文件
// 8
//
// Created by 李迪 on 15-7-26.
// Copyright (c) 2015年 李迪. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
@interface ViewController : UIViewController
{
IBOutlet UILabel * result;
}
@property(nonatomic,retain) UILabel *result;
-(IBAction)agreeDisagree;
-(IBAction)leftCenterRight;
-(IBAction)oneToHundred;
-(IBAction)russianRoulette;
@end
.m文件
// ViewController.m
// 8
//
// Created by 李迪 on 15-7-26.
// Copyright (c) 2015年 李迪. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize result;
-(IBAction)agreeDisagree{
int rNumber = rand()%2;
switch(rNumber){
case 0:
result.text = @"agree";
break;
case 1:
result.text = @"disagree";
break;
}
}
-(IBAction)leftCenterRight{
int rNumber = rand()%3;
switch (rNumber) {
case 0:
result.text = @"left";
break;
case 1:
result.text = @"center";
case 2:
result.text = @"right";
}
}
-(IBAction)oneToHundred{
int rNumber = rand()%100;
result.text = [NSString stringWithFormat:@"%d",rNumber];
}
-(IBAction)russianRoulette{
int rNumber = rand()%6;
switch (rNumber) {
case 0:
result.text = @"bumm";
break;
default:
result.text = @"Take easy!";
break;
}
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
本程序结合前面学到的知识主要总结两个关于程序的知识点:
1:rand()%num (num是一个整数)
在java里面获取一个随机数是random,而OC里面可以用到rand()获取一个随机数,而且我查了一下,获取的这个随机数还是范围很大的随机数;rand()%num是获取一个范围是从0~num-1的一个随机数,因为%表示求余数。
2:就是OC里面表示条件的时候,如果条件比较多的话,可以用switch语句。表现形式如下:
int num1 = rand()%num;
switch(num1){
case 0:
执行语句;
break;
case 1:
执行语句;
break;.........(case可以有很多个,但是不能超出num1的范围)default:
默认执行,即上面的case都不满足的情况下执行
break;(default可以省略不写)
}
这样的话有很多种条件的语句就可以很简单的表示出来。