Is there a trunc function in C++?

后端 未结 7 814
情歌与酒
情歌与酒 2021-01-19 04:52

I searched around and couldn\'t find the trunc function for C++. I know I can do this:

int main()
{
    double a = 12.566789;
    cout <<          


        
相关标签:
7条回答
  • 2021-01-19 05:23

    Sure. Use the trunc() function from math.h. It's a C function, but it works as well in C++ as it does in C. If you want to keep a couple digits, you can always:

    double a = 12.566789;
    double b = trunc(a * 100) / 100.0;
    
    0 讨论(0)
  • 2021-01-19 05:34

    use ceil or floor from cmath

    0 讨论(0)
  • 2021-01-19 05:35

    If your C library is so old that it lacks a trunc function (specified in C99), you can easily implement one based on floor and ceil (specified in C89)

    double trunc(double d){ return (d>0) ? floor(d) : ceil(d) ; }
    
    0 讨论(0)
  • 2021-01-19 05:37

    trunc is there, in <cmath>:

    #include <iostream>
    #include <cmath>
    
    int main() {
            std::cout << trunc(3.141516) << std::endl; 
    }
    

    I suppose you're looking for something else?

    0 讨论(0)
  • 2021-01-19 05:39

    There's a trunc function in C that you can use in C++

    trunc(a*100)/100
    

    Keep in mind that you still have to specify formatting requests, because floating point can't represent all real numbers exactly, and you could get output like 12.5600000001 or 12.55999999 if you don't tell the output code the precision you want.

    TL;DR

    Use the following for output:

    cout << setprecision(2) << fixed << a<< endl;
    

    And the following if you need a truncated result somewhere during a mathematical calculation:

    trunc(a*100)/100
    

    (Or better yet, use fixed-point math.)

    0 讨论(0)
  • 2021-01-19 05:39

    If you're using an ancient C or C++ library that doesn't implement trunc, use boost::math::trunc.

    0 讨论(0)
提交回复
热议问题