Saturday, October 5, 2013

Format a Positive Real Number

Consider a positive real number given in the form F.I (the float form). Treating F as the fractional part and I as the integral part, print the number in the form GH.J where H is a sequence of # (hashes) such that the decimal point always occurs at the sixth (6th) position from the left and G is I with only the significant digits, and J is F with only the significant digits.

Terminate your output with a newline. Assume that the fractional part F always has no leading zeros and both F and I have at most five (5) significant digits.

Sample Input and Output:

Input:
10000.6660
Output:
6660#.1
Input:
990.0080
Output:
80###.99
Input:
101.11111
Output:
11111.101
Input:
31644.0
Output:
#####.31644

Solution:

#include <stdio.h>
#include <stdlib.h>

void main()
{
    int end,start,start_temp;
    char c[20];
    int i,j,flag=0;
    char out_end[10];
    char out_start[10];

    for(i=0;i<20;i++)
    c[i]='\0';

    //Reading values
    scanf("%s",c);    
    i=0;

    //Extracting starting digits for end
    while(c[i]!='.')    
    {
        if(c[i]=='.' && flag==0)
        {
            flag=1;
        }
        else if(flag==0)

        out_end[i]=c[i];
        i++;    
    }
    
    out_end[i]='\0';
    end=atoi(out_end);

    while(end%10==0)
    {
        end=end/10;
    }
    
    i=0;
    flag=0;

    //Extracting digits after decimal
    while(c[i]!='\0')    
    {
        if(c[i]=='.' && flag==0)
        {
            flag=1;
            j=0;
        }
        else if(flag==1)
        {
            out_start[j]=c[i];
            j++;
        }
        i++;    
    }

    out_start[j]='\0';
    start=atoi(out_start);
    i=0;
    start_temp=start;

    //Removing 0
    while(start_temp/10>0)    
    {
        start_temp/=10;
        i++;
    }
    i=5-i;
    
    //Output
    if(start>0)
    printf("%d",start);
    else 
    i=6;
    for(j=1;j<i;j++)
    printf("#");
    printf(".%d\n",end);
}

No comments:

Post a Comment