iOS objective-C: using modulo on a float to get “inches” from Feet

痞子三分冷 提交于 2019-12-30 08:13:02

问题


I am trying to make a simple objective-C height converter. The input is a (float) variable of feet, and I want to convert to (int) feet and (float) inches:

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

However, I keep getting an error from xcode, and I realized that the modulo operator only works with (int) and (long). Can someone please recommend an alternative method? Thanks!


回答1:


Even modulo works for float, use :

fmod()

You can use this way too...

float totalHeight = 5.122222;
float myFeet = (int) totalHeight; //returns 5 feet
float myInches = fmodf(totalHeight, myFeet);
NSLog(@"%f",myInches);



回答2:


Why don't you use

CGFloat myInches = totalHeight - myFeet;



回答3:


As answered earlier, subtracting is the way to go. Just remember to convert the one tenths of feet to inches by multiplying with 12:

float totalHeight = 5.122222;
int myFeet = (int) totalHeight;
float myInches = (totalHeight - myFeet) * 12;


来源:https://stackoverflow.com/questions/16394216/ios-objective-c-using-modulo-on-a-float-to-get-inches-from-feet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!