我对 Objective-c 还很陌生。
我正在尝试创建一个以英寸或厘米为单位的函数,并将这些值转换为相反的公制系统。
鉴于我不知道如何相应地设置变量,我目前正在努力研究如何在 Objective-C 中做数学方程。因为我总是从 XCode 中得到一些错误,说变量是 int 但不应该是 int 或者指针错误等等......基本上......我不知道如何进行数学......
目的是传递存储在其他地方的字符串 5’11”
或 1.80 cm
并将其转换为相反的公制系统。
下面的代码尝试将英寸转换为厘米......如果我们传递 5'5”,数学方程应为 ((5 * 12) + 3) * 2.54
这是相等的到 180.34
,我从函数中看到的格式化结果是 1.80 cm
下面的代码是我所得到的,但它对我不起作用。如果有人可以告诉我如何在我的代码中执行此操作,我将不胜感激。
- (NSString *)returnRightMetric:(NSString *)theMeasure typeOfMetricUsed:(NSString *)metricType
{
if ([metricType isEqualToString:@"inches"]) {
NSArray* theConvertion = [theMeasure componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:@"’”"]];
NSInteger* value1 = [theConvertion[0] intValue];
NSInteger* value2 = [theConvertion[1] intValue];
float *number = ((value1 * 12) + value2) * 2.54;
///.....
} else if ([metricType isEqualToString:@"cm"])
{
}
return result;
}
最佳答案
出现此问题的原因是您在 NSInteger
和 float
中使用了指针。我已经修改了您的方法,实现了厘米和英寸,如下所示:
- (NSString *)returnRightMetric:(NSString *)theMeasure typeOfMetricUsed:(NSString *)metricType
{
NSString *result = nil;
if ([metricType isEqualToString:@"inches"]) {
NSArray* theConvertion = [theMeasure componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:@"’”"]];
NSInteger value1 = [theConvertion[0] intValue];
NSInteger value2 = [theConvertion[1] intValue];
float number = ((value1 * 12) + value2) * 2.54;
result = [NSString stringWithFormat:@"%.02f cm", round(number * 100.0) / 100.0];
} else if ([metricType isEqualToString:@"cm"]) {
float value = [theMeasure floatValue];
float number = value / 2.54;
if (number > 12.0) {
result = [NSString stringWithFormat:@"%i’%i”", (int)floor(number / 12.0), (int)number % 12];
} else {
result = [NSString stringWithFormat:@"0’%i”", (int)round(number)];
}
}
NSLog(@"result: %@", result);
return result;
}
一些测试:
[self returnRightMetric:@"5’11”" typeOfMetricUsed:@"inches"];
[self returnRightMetric:@"180.34 cm" typeOfMetricUsed:@"cm"];
[self returnRightMetric:@"0’11”" typeOfMetricUsed:@"inches"];
[self returnRightMetric:@"27.94 cm" typeOfMetricUsed:@"cm"];
输出:
result: 180.34 cm
result: 5’11”
result: 27.94 cm
result: 0’11”
关于iphone - 将英寸转换为厘米,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15955914/