如何在 Xcode 7 和 Swift 2 中创建具有特殊格式的随机数
How to create Random number with special format in Xcode 7 and Swift 2
我的编码有问题。我正在尝试生成一个 8 位数的随机数,例如:12345676,它显示这样的数字 12 34 56 76。两位数,所以一个空白 space,一些两位数和其他空白 space...谢谢,
我使用的代码是:
NSMutableArray *numbers;
for(int i=0; i<3; i++){
float l_bound = 10;
float h_bound = 99;
float rndValue = (((float)arc4random()/0x100000000)*(h_bound-l_bound)+low_bound);
int intRndValue = (int)(rndValue + 0.5);
[numbers addObject: intRndValue]
;}
NSString *result = [numbers componentsJoinedByString:@" "];
至少你得初始化数组
NSMutableArray *numbers = [NSMutableArray array];
并且您只能将对象添加到数组中,而不是像 int
或 float
.
这样的标量类型
NSString *intRndValue = [NSString stringWithFormat:@"%.0f", (rndValue + 0.5)];
在 Swift 2 你可以写
var numbers = Array<String>()
let l_bound : UInt32 = 10
let h_bound : UInt32 = 99
for i in 0..<3 {
let rndValue = Int(arc4random_uniform(h_bound - l_bound) + l_bound)
numbers.append("\(rndValue)")
}
let result = numbers.joinWithSeparator(" ")
我的编码有问题。我正在尝试生成一个 8 位数的随机数,例如:12345676,它显示这样的数字 12 34 56 76。两位数,所以一个空白 space,一些两位数和其他空白 space...谢谢,
我使用的代码是:
NSMutableArray *numbers;
for(int i=0; i<3; i++){
float l_bound = 10;
float h_bound = 99;
float rndValue = (((float)arc4random()/0x100000000)*(h_bound-l_bound)+low_bound);
int intRndValue = (int)(rndValue + 0.5);
[numbers addObject: intRndValue]
;}
NSString *result = [numbers componentsJoinedByString:@" "];
至少你得初始化数组
NSMutableArray *numbers = [NSMutableArray array];
并且您只能将对象添加到数组中,而不是像 int
或 float
.
NSString *intRndValue = [NSString stringWithFormat:@"%.0f", (rndValue + 0.5)];
在 Swift 2 你可以写
var numbers = Array<String>()
let l_bound : UInt32 = 10
let h_bound : UInt32 = 99
for i in 0..<3 {
let rndValue = Int(arc4random_uniform(h_bound - l_bound) + l_bound)
numbers.append("\(rndValue)")
}
let result = numbers.joinWithSeparator(" ")