C language practice (1)

Source: Internet
Author: User

I. A three-day bug

Int fscanf (File * stream, char const * format ,...)

Int scanf (char const * format ,...)

Int sscanf (char const * string, char const * format ,...)

Function to read characters from the input source. The Return Value of the function is the number of input values for conversion.

{

Int A, B;

Sscanf (buffer, "% d", "% d", & A, & B );

}

{

Unsigned int A, B;

Sscanf (buffer, "% d", "% d", & A, & B );

} // An error occurs. The format code is D, which is an integer in decimal format. The data is stored as a signed number. If the integer parameter is longer or shorter than the default integer parameter, omitting a qualifier in the format code is a common error.

{

Unsigned short A, B;

Sscanf (buffer, "% HD", "% HD", & A, & B );

} // Qualifier H. modify the meaning of some format code. HD is no longer the default integer, but short Int.

2. Floating Point comparison

In the program, F1 = F2, but it is clearly equal, but in the program it is done according to the inequality, floating point numbers cannot be compared like this; for example

Float F = 25.095;

If (F = 25.095) printf (,); // The result is that F is not equal to 25.095. This is because the value of 25.095 is expressed as 25.0949999 because it cannot be expressed as a floating point.

We should make a comparison:

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

After a floating point operation, the result is rounded to the memory, which may lead to errors. Therefore, we should try to use high-precision data types, such as when using gcc, we try to use long double instead of double or float, which reduces the chance of many errors. As a general comparison, you can set the difference precision and then compare it.

Complete comparison:

Bool isequal (float a, float B, float abserror, float relerror)
{
If (A = B) Return true;
If (FABS (a-B) <abserror) return true;
If (FABS (A> B) Return (FABS (a-B)/A> relerror )? True: false;
Return (FABS (a-B)/B> relerror )? True: false;
}

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.