将厘米转换为英尺和英寸,反之亦然不同的输出?

convert centimeter to feet and inches and vice versa different output?

我正在使用以下代码将厘米转换为英尺和英寸,但它没有按预期工作。

+ (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)];
}

我正在使用以下代码将英尺和英寸字符串转换为厘米

NSInteger totalInches = ([self.Feets integerValue] * 12) + [self.Inches integerValue];

            self.heightInCm = totalInches * 2.54;

但是当我将 self.heightInCm 转换回英尺和英寸时,它没有提供正确的 value.Could 某人 post 这方面的完美工作示例

一般来说,您的代码可以正常工作。有一些小问题,例如fabsf 不是必需的,但根据我的测试,它运行良好。

您遇到的问题可能是因为在转换为英尺和英寸时,您对值进行了四舍五入。

一英寸等于2.54 cm。如果您将英寸四舍五入为整数值,则您的最大精度将为 2.54 cm.

例如5'11'就是180,3 cm6'0182,8cm。这两个值之间的任何值(例如 181182183 将四舍五入为 5'116'0)。

正确的解决方案取决于您的用例。如果您只向用户显示值,请以厘米为单位,并在显示时仅转换为英尺和英寸。如果您的用户正在输入该值,您无法使其更精确,但您可以将 accept/display 英寸作为十进制值(将 roundf(myInches) 替换为 myInches 并使用 [self.inches floatValue] ).

根据评论,当计算为 11.8 的英寸被四舍五入为 12 时,您也遇到了舍入问题,这在结果中没有意义。我建议将算法修改为以下内容:

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 英寸的问题,因为圆形应用于以英寸为单位的总长度。

这是 Swift 版本,用于将厘米转换为英尺和英寸:

SWIFT 4

func showFootAndInchesFromCm(_ cms: Double) -> String {

      let feet = cms * 0.0328084
      let feetShow = Int(floor(feet))
      let feetRest: Double = ((feet * 100).truncatingRemainder(dividingBy: 100) / 100)
      let inches = Int(floor(feetRest * 12))

      return "\(feetShow)' \(inches)\""
}