I have to set up a program that has the user enter the miles they traveled, the hours it took and then, the output has to give them the mph and round it. How do I get started?
Rounding form a float to an int in C++
Collapse
X
-
First, let's clarify the requirements ...- How many decimal digits do you have to round to? (The obvious answer is zero, but I'm asking to make sure.)
- There are several common rounding algorithms: round toward zero (truncation); round towards +/- infinity; round-up (ceil function), round-down (floor function), and round-to-nearest. Which one do you intend to use?
Hint: What happens when you assign a floating-point value to an integral variable? For example:
Code:int a; double b = 4.75; a = b;
Comment
-
hi
You can user floor and ceil funtion in c++.
If decimal part of your number is greater than or equal to 0.5 you can use ceil function and if decimal part is lesser than 0.5 you can use floor function.
To know the decimal part pass the double value to an integer variable and then subtract that integer value from double value. After that use if else statements to choose floor or ceil function.
You can also use modf function that will seperate integer part and fractional part from a double variable.
Vipin SharmaComment
-
Whether the quoted algorithm works for negative numbers depends on the precise meaning of if decimal part of your number is less than 0.5 for that case.Comment
-
This forum has a link to the C FAQ index in the PLEASE READ FIRST thread.
Take a look at C FAQ #14.6.Comment
-
hi,
Yes Donbock is right, this algorithm might not be useful in case of negative numbers. As long as we are dealing with speed and time algorithm works fine.
Vipin SharmaComment
-
//25/09/09 15:03 you could tackle it along these lines.
Code:double y=<MPH>; if((y-int(y))<0.5) cout<<"average miles/hour is: "<<floor(y)<<endl; else cout<<"average miles/hour is: "<<ceil(y)<<endl;
Comment
Comment