How to only accept a certain precision (so many decimals places) in scanf?

后端 未结 4 1372
刺人心
刺人心 2020-12-04 01:33

In scanf() function I want to take only upto decimal values.Can we achieve it? For example for displaying upto two decimal places we use printf(\"%.2f\",

4条回答
  •  无人及你
    2020-12-04 02:09

    1. include stdlib.h
    2. include math.h
    3. IF function pow from math.h fails to compile, must compile with gcc file.c -o file -lm
    4. TRY example :

    Input : 13254.45488

    Output: 13254.45

    void main()
    {
    
        int x,y,i ;
        int precision = 2 ; /*Insert precision here*/
        char a[precision] ;
        long double z,result ;
    
        printf( "Input : " );   
        scanf( "%d" , &x );
    
        for ( i = 0 ; i <= precision  ; i++ )
        {
    
            a[i] = getchar();
    
            if ( a[i] == 10 ) break;
    
        }
        
        a[0] = '0';
        a[i] = '\0';
    
        y = atoi(a);
        z = y / pow( 10 , i-1 );
        result = x ;
    
        if ( z != 0 ) result = result + z ;
    
        printf( "Output: " );   
        printf( "%.*Lf\n", i-1 , result );
    
    }
    

提交回复
热议问题