C++/c++

Advertisement


Question
could u pls help mi.hw should i truncate a decimal value into a whole number.example:27.56,round off will be 28.

Answer
When a floating point value is converted to an integer type, the conversion truncates - that is, the fractional part is discarded. The simplest way, therefore, is to add 0.5 to the floating point value and then convert it to an int.

#include <iostream>

int to_nearest_int( double value )
{ return value + 0.5 ; }

int main()
{
   double v ;
   while( std::cin >> v ) std::cout << to_nearest_int(v) << '\n' ;
}  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.