The C language converts a numeric string to a number corresponding to this string (including positive floating-point numbers, negative floating-point function prototypes: Double my_atof (char *str)

Source: Internet
Author: User

Write a function that converts a numeric string to a number corresponding to the string (including positive floating-point numbers, negative floating-point numbers)

For example: "12.34" returns 12.34

"-123.34" return-123.34

Function prototypes: Doublemy_atof (char *str)

Tips:

You need to judge the minus sign in the function, the decimal point, and whether it is a numeric character. When judging a decimal point, you need to define a counter to calculate the number of numeric characters after the decimal point.

#include <stdio.h> #include <math.h>double my_atof (char *str) {    char *ch = str;    int flag=1;    int point=0;    int count=0;    Double sum = 0;    while (*ch! = ')        } {            if (*ch = = '-')      //Judging minus sign            {                flag =-1;                ch++;            }            if (*ch = = '. ')                  {                point=1;                ch++;            }            if (*ch >= ' 0 ' && *ch <= ' 9 ')            {                sum=sum*10+ (*ch-' 0 ');                ch++;            }            if (point==1)    //encounters a decimal counter plus 1            {                count++;            }        }        Sum=flag*sum*pow (10,-count);    return sum;} int main () {    char *str= "12.83";    Double N;    N=my_atof (str);    printf ("%f\n", n);    return 0;}



The C language converts a numeric string to a number corresponding to this string (including positive floating-point numbers, negative floating-point function prototypes: Double my_atof (char *str)

Related Article

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.