Is there a trunc function in C++?

后端 未结 7 813
情歌与酒
情歌与酒 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: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.)

提交回复
热议问题