gpt4 book ai didi

iOS 转换器应用程序,度量之间的连接

转载 作者:行者123 更新时间:2023-11-28 20:07:59 26 4
gpt4 key购买 nike

我想知道是否有人可以帮助我如何在度量之间建立联系,例如我如何计算图片中厘米和英寸之间的关系。这是我的学校项目应用程序,除了那部分,它或多或少已经完成了。所以我正在从 plist 中读取值,并根据我在选择器中的第一列显示第二和第三列。所有单位和措施都是从 plist 中读取的。以能量、距离、体积等为键。

那么在度量之间建立联系的最简单方法是什么?我最简单也是最业余的想法是编写很长的代码,像这样:

if (first column == distance){
if (second column ==millimeter) {
case 0: if (third column == millimeter) then result=x*1;
case 1:if (third column == centimeter) then result=0/100;
.
.
.
}
if (second column == centimeter){
case 0:
case 1:
.
.
.
}}

这将导致大约 1000 行不必要的代码。有没有人有更好的主意?提前致谢。

最佳答案

整个事情都可以用数据来完成,没有if,没有switches……只是需要稍微组织一下。请考虑以下事项:

@property (strong, nonatomic) NSArray *distanceIndex;
@property (strong, nonatomic) NSArray *weightIndex;

@property (strong, nonatomic) NSArray *distanceConversion;
@property (strong, nonatomic) NSArray *weightConversion;

- (void)initConversions {

// we get strings in as our units, so we need to convert these to array indexes
// make up our own convention, meters=0, inches=1, etc

self.distanceIndex = @[@"meters", @"inches", @"miles"];
self.weightIndex = @[@"grams", @"ounces", @"pounds"];

// you might read these from a file, but in code, just to illustrate...
// the order follows the order of the index. so the meters line is first
// and the conversion factors are meters->meters, meters->inches, meters->miles etc.
// notice the 1.0's on the diagonal, and that numbers reflected across
// the diagonal are reciprocals

self.distanceConversion =
@[ @[@"meters", @[@1.0, @39.37, @0.000621]],
@[@"inches", @[@0.254, @1.0, @0.00001578]],
@[@"miles ", @[@1609.0, @63360.0, @1.0]] ];

// and so on... same thing for self.weightConversions
}

- (double)convertDistance:(double)value from:(NSString *)fromUnits to:(NSString *)toUnits {

NSUInteger fromIndex = [self.distanceIndex indexOfObject:fromUnits];
NSUInteger toIndex = [self.distanceIndex indexOfObject:toUnits];

// throw an exception if passed units that we don't recognize
NSAssert(fromIndex != NSNotFound && toIndex != NSNotFound, @"could not find units");

NSArray *conversionRow = self.distanceConversion[fromIndex][1];
NSNumber *conversionNumber = conversionRow[toIndex];
double conversion = [conversionNumber doubleValue];

return value * conversion;
}
- (double)convertWeight:(double)value from:(NSString *)fromUnits to:(NSString *)toUnits {

// same idea here, if you have the weight conversion data
return 0;
}

关于iOS 转换器应用程序,度量之间的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21340646/

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