gpt4 book ai didi

ios - 如何比较两个数字并选择最小的数字继续执行?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:26:00 27 4
gpt4 key购买 nike

假设 number = 0 和 otherNumber = 10。循环将执行。但是如果 number = 10 和 otherNumber = 0 怎么办。我希望编译器选择最小的数字并使用它继续。

我目前的代码在这里:

- (NSString *) stringWithNumbersBetweenNumber:(NSInteger)number andOtherNumber: (NSInteger)otherNumber {
if (number <= otherNumber) {
NSMutableString *indices = [NSMutableString stringWithCapacity:1];
for (NSInteger i= number; i <= otherNumber; i++) {
[indices appendFormat:@"%d", i];
}
} else {
NSMutableString *indices = [NSMutableString stringWithCapacity:1];
for (NSInteger i= otherNumber; i <= number; i++) {
[indices appendFormat:@"%d", i];
}
}
return @"%@", indices;
}

最佳答案

一个简单的解决方法是将 indices 的声明移到条件之外:

- (NSString *) stringWithNumbersBetweenNumber:(NSInteger)number andOtherNumber: (NSInteger)otherNumber {
NSMutableString *indices = [NSMutableString stringWithCapacity:1];
if (number <= otherNumber) {
for (NSInteger i= number; i <= otherNumber; i++) {
[indices appendFormat:@"%d", i];
}
} else {
for (NSInteger i= otherNumber; i <= number; i++) {
[indices appendFormat:@"%d", i];
}
}
return indices;
}

你可以像这样进一步统一你的:

- (NSString *) stringWithNumbersBetweenNumber:(NSInteger)number andOtherNumber: (NSInteger)otherNumber {
NSInteger from, to;
if (number <= otherNumber) {
from = number;
to = otherNumber;
} else {
from = otherNumber;
to = number;
}
NSMutableString *indices = [NSMutableString stringWithCapacity:1];
for (NSInteger i= from; i <= tp; i++) {
[indices appendFormat:@"%d", i];
}
return indices;
}

关于ios - 如何比较两个数字并选择最小的数字继续执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30971131/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com