10

我正在尝试制作一个简单的 Objective-C 高度转换器。输入是英尺的 (float) 变量,我想转换为 (int) 英尺和 (float) 英寸:

float totalHeight = 5.122222;
float myFeet = (int) totalHeight; //returns 5 feet
float myInches = (totalHeight % 12)*12; //should return 0.1222ft, which becomes 1.46in

但是,我不断收到来自 xcode 的错误,并且我意识到模运算符仅适用于 (int) 和 (long)。有人可以推荐一种替代方法吗?谢谢!

4

3 回答 3

26

即使模数也适用于浮点数,请使用:

fmod()

你也可以用这种方法...

float totalHeight = 5.122222;
float myFeet = (int) totalHeight; //returns 5 feet
float myInches = fmodf(totalHeight, myFeet);
NSLog(@"%f",myInches);
于 2013-05-06T07:45:54.480 回答
1

你为什么不使用

CGFloat myInches = totalHeight - myFeet;
于 2013-05-06T07:43:46.157 回答
0

如前所述,减法是要走的路。只需记住乘以 12 将十分之一英尺转换为英寸:

float totalHeight = 5.122222;
int myFeet = (int) totalHeight;
float myInches = (totalHeight - myFeet) * 12;
于 2013-05-06T07:53:21.960 回答