By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,948 Members | 804 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,948 IT Pros & Developers. It's quick & easy.

Hey,n00b question converting cm to inches,then yards,feet,inches

P: 3
Hey I have this prog that i'm working on, starting my first c++ class and kind of a n00b to programming

here it is

#include <iostream>

#include <cstdlib>

using namespace std;

int main()

{ int remainder,remainder2,yards,feet,inches;

float centi,inche5;

cout<<"What is the length in Centimeters"<<endl;


//convert to nearest inch



//Compute Yards


//Drop Remainder To Feet


//Compute Feet


//Drop Remainder To Inches






return 0;


i used static_cast to convert float to int without runtime errors, the problem is that static_cast rounded down so the output tended to be 1 less inch then what's mathmatically there a better way to convert float to int or somehow name all variables as int but still keep the conversion of cm/2.54?

thanks for all your help
Sep 23 '06 #1
Share this Question
Share on Google+
4 Replies

P: 3
also.. basically what i must do.. is convert cm to inches... round to the nearest inch, then my output must be in yards, feet, inches i figured that i could just use int as in (int)inches=(int)cm/2.54 but since i'm / an int by not an int it gives a runtime error
thanks for all your help once again
Sep 23 '06 #2

P: 3
bump...please if anyone can give me any tips they are greatly appreciated!
Sep 23 '06 #3

P: 293
Tip: Don't re-invent the wheel.
Sep 24 '06 #4

Expert Mod 5K+
P: 8,916
D_C has a good point but on the subject of converting float to int then

assuming that the value of the float is in range for the int then you will always loose the decimal places. When you put your conversion in place you will have to decided if that is ok if it isn't then you will need to do something to correct the conversion.

You instance in your case (converting cm to inches) you may decided hat you actually want the value to the nearest inch. This means that for decimals >= x.5 you want to round up to (x+1) and for values < x.5 round down to x.

inches = (int)inche5;

rounds downall fractions but you can achieve the nearest inch this way

inches = (int)(inche5+0.5);

This works because for values of inche5 >= x.5 then inche5 + 0.5 is >= x+1 so inches takes the value x+1. simialrly for values <x.5 inche5 + 0.5 > x+1 so inches takes the value x.
Sep 24 '06 #5

Post your reply

Sign in to post your reply or Sign up for a free account.