how to make negative numbers into positive

前端 未结 8 1930
天命终不由人
天命终不由人 2021-02-01 14:09

I am having the negative floating point number as:

a = -0.340515;

to convert this into positive number I used the abs() method as:



        
8条回答
  •  半阙折子戏
    2021-02-01 14:50

    Why do you want to use strange hard commands, when you can use:

    if(a < 0)
        a -= 2a;
    

    The if statement obviously only applies when you aren't sure if the number will be positive or negative.

    Otherwise you'll have to use this code:

    a = abs(a) // a is an integer
    a = fabs(a) // a is declared as a double
    a = fabsf(a) // a is declared as a float (C++ 11 is able to use fabs(a) for floats instead of fabs)
    

    To activate C++ 11 (if you are using Code::Blocks, you have to:

    1. Open up Code::Blocks (recommended version: 13.12).
    2. Go to Settings -> Compiler.
    3. Make sure that the compiler you use is GNU GCC Compiler.
    4. Click Compiler Settings, and inside the tab opened click Compiler Flags
    5. Scroll down until you find: Have g++ follow the C++ 11 ISO C++ language standard [-std=c++11]. Check that and then hit OK button.
    6. Restart Code::Blocks and then you are good to go!

    After following these steps, you should be able to use fabs(a) for floats instead of fabsf(a), which was used only for C99 or less! (Even C++ 98 could allow you to use fabs instead of fabsf :P)

提交回复
热议问题