将厘米转换为英尺和英寸,反之亦然? [英] convert centimeter to feet and inches and vice versa different output?
问题描述
我正在使用以下代码将厘米转换为英尺和英寸,但无法按预期工作。
I am using following code to convert centimeters into feet and inches but it doesn't work as expected.
+ (NSString*)getfeetAndInches:(float)centimeter {
float totalHeight = centimeter * 0.032808;
float myFeet = (int)totalHeight; //returns 5 feet
float myInches = fabsf((totalHeight - myFeet) * 12);
NSLog(@"%f",myInches);
return [NSString stringWithFormat:@"%d' %0.0f\"",(int)myFeet,roundf(myInches)];
}
我正在使用以下代码将英尺和英寸字符串转换为厘米
I'm using the following code to convert feet and inches string into centimeter
NSInteger totalInches = ([self.Feets integerValue] * 12) + [self.Inches integerValue];
self.heightInCm = totalInches * 2.54;
但是当我转换 self.heightInCm
它无法提供正确的价值。有人可以张贴一个完美的工作示例吗?
But when I convert self.heightInCm
back to feet and inches it does not provide correct value.Could someone post a perfect working example of this
推荐答案
通常,代码可以正常工作。存在一些小问题,例如 fabsf
不是必需的,但从我的测试来看,它很好用。
In general, your code works correctly. There are some minor issues, e.g. the fabsf
is not necessary but from my testing it works well.
您遇到的问题可能是由于以下事实引起的:转换为英尺和英寸时,您正在舍入值。
The problem you have is probably caused by the fact, that when converting to feets and inches, you are rounding off values.
英寸等于 2.54 cm
。如果您是圆形的将英寸换算为整数值,则最大精度将为 2.54 cm
。
An inch is equal to 2.54 cm
. If you are rounding inches to an integer value, your maximum precision will be 2.54 cm
.
例如, 5'11'
是 180,3厘米
。 6’0
是 182,8厘米
。这两个值之间的任何值(例如 181
, 182
, 183
将四舍五入为 5'11
或 6'0
)。
For example, 5'11'
is 180,3 cm
. 6'0
is 182,8cm
. Anything between those two values (e.g. 181
, 182
, 183
will get rounded to either 5'11
or 6'0
).
正确的解决方案取决于您的用例。如果仅向用户显示值,则将其保持为厘米,并且在显示时仅转换为英尺和英寸。如果您的用户正在输入值,则无法使其更精确,但可以接受/显示英寸作为十进制值(将 roundf(myInches)
替换为 myInches
并使用 [self.inches floatValue]
)。
The correct solution depends on your use case. If you are only presenting the values to the user, keep them in centimeters and only convert to feet&inches when displaying. If your users are entering the value, you can't make it more precise but you can accept/display inches as a decimal value (replace roundf(myInches)
with just myInches
and use [self.inches floatValue]
).
从注释中,当按 11.8
计算的英寸四舍五入到 12
时,您还会遇到舍入问题。结果有意义。我建议将算法改写为以下内容:
From the comments, you also have a rounding problem when inches calculated as 11.8
are rounded up to 12
which doesn't make sense in the result. I recommend to rework the algorithm into the following:
const float INCH_IN_CM = 2.54;
NSInteger numInches = (NSInteger) roundf(centimeter / INCH_IN_CM);
NSInteger feet = numInches / 12;
NSInteger inches = numInches % 12;
return [NSString stringWithFormat:@"%@' %@\"", @(feet), @(inches)];
这很容易解决12英寸的问题,因为将回合应用于英寸的总长度。
That will easily solve the 12 inch problem because the round is applied to the total length in inches.
这篇关于将厘米转换为英尺和英寸,反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!