Write a program to convert a floating-point number to a string.
Example:
Input: n=23.686999
Output: "23.8969"
Approach
C
#include <stdio.h>#include <math.h>//function to reverse a stringvoid reverse(char *str, int len){int i = 0, j = len - 1, temp;//apply two pointer approachwhile (i < j){//swap the first and lasttemp = str[i];str[i] = str[j];str[j] = temp;//increment firsti++;//decrement lastj--;}}//function to convert interer to stringint intToStr(int x, char str[], int d){int i = 0;while (x > 0){//convert to characterstr[i++] = (x % 10) + '0';x = x / 10;}// If number of digits required is more, then// add 0s at the beginningwhile (i < d)str[i++] = '0';reverse(str, i);str[i] = '\0';return i;}// Converts a floating point number to string.void ftoa(float n, char *res, int afterpoint){//integer partint ipart = (int)n;// floating partfloat fpart = n - (float)ipart;// convert integer part to stringint i = intToStr(ipart, res, 0);// check for display option after pointif (afterpoint != 0){//put . to the resultres[i] = '.';fpart = fpart * pow(10, afterpoint);//convert into to string after .intToStr((int)fpart, res + i + 1, afterpoint);}}int main(){char res[20];float n = 23.896999;//only 4 numbers come after decimalftoa(n, res, 4);printf("%s",res);return 0;}
No comments:
Post a Comment