About the loss of pow floating point Precision

Source: Internet
Author: User
/* A very simple question asked me by my dormitory students is to convert the string output after the number is in reverse order to a numerical value. The students use the common function pow, and the code logic is correct, but I don't understand why the answer is wrong, and it's only one or two. With the help of Tom, I began to realize the loss of pow precision. check cplusplus.com to find the following problems: double pow (double base, double exponent); long double pow (long double base, long double exponent); float pow (float base, float exponent); double pow (double base, int exponent); long double pow (long double base, int exponent); pow function does not exist pow (int), also That is to say, 10 of the input pow (10, n) will first be converted to double, which leads to an error when the number is large. It seems that common functions also need to pay attention to the details! */# Include <stdio. h> # include <math. h> int a [1000]; int main () {int I, x, n = 0, t, sum = 0, j = 0; scanf ("% d ", & I); x = I; printf ("in reverse order:"); while (x) {t = x % 10; printf ("% d", t ); a [j ++] = t; x/= 10;} printf ("\ n");/* for (int I = 0; I <j; I ++) sum = sum * 10 + a [I]; */while (j> = 0) {-- j; sum + = a [j] * (int) (pow (10, n) + 0.5); // If 0.5 is not added here and rounded to int, the precision will be lost. n ++ ;} printf ("sum = % d \ n", sum); return 0 ;}

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.