The C language compares the two floating point numbers for the same method, FABS and ABS

Source: Internet
Author: User

I encountered this problem during the interview today, but I was confused at the time. After all, I never used it very much. I remember reading it before and I cannot remember it now! This is a basic C language and is usually used for interviews!

You cannot use = to determine whether the two floating point numbers are equal or not. An error occurs! The two numbers that are clearly equal are not equal!

For two floating point numbers, you can only subtract them and compare them with the preset precision. Remember to take the absolute value!

If (FABS (F1-F2) <pre-specified precision ){...}

Example

# Define Epsilon 0.000001 // If (FABS (Fa-FB) <epsilon) {printf ("fa <FB \ n") According to precision requirements ");}

FABS and ABS Functions

Mathematical function: FABS
Prototype: extern float FABS (float X );

Usage: # include <math. h>

Function: calculates the absolute value of floating point X.

Description: calculation | x |. If X is not negative, X is returned. Otherwise,-X is returned.

Example:

    // fabs.c            #include <syslib.h>      #include <math.h>      main()      {        float x;                clrscr();        // clear screen        textmode(0x00);  // 6 lines per LCD screen                x=-74.12;        printf("|%f|=%f\n",x,fabs(x));        x=0;        printf("|%f|=%f\n",x,fabs(x));        x=74.12;        printf("|%f|=%f\n",x,fabs(x));                getchar();        return 0;      }

The ABS function is for integers.
#include <stdio.h>#include <math.h>int main(){ int x=-10; printf("%d",abs(x));}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.