C Tutorial/Data Type/float Display

Материал из C\C++ эксперт
Версия от 10:32, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

%6f limits the output to only six digits

#include <stdio.h>
main(){
   
    printf("%6.1f", 123456.123456);
    printf("\n%6.2f", 123456.123456);
    printf("\n%6.3f", 123456.123456);
    printf("\n%6.4f", 123456.123456);
}
123456.1
      123456.12
      123456.123
      123456.1235

Displaying Floating-Point Data Types with printf: %f

#include <stdio.h>
main(){
    float result;
    result = 3.123456;
    printf("The value of result is %f", result);
}
The value of result is 3.123456

%e displays numbers in scientific format.

#include <stdio.h>
main(){
   
    printf("%e", 123456.123456);
    printf("\n%e", 12345612345.6);
}
1.234561e+05
      1.234561e+10

%g displays a floating-point number in either the %f or %e (scientific) format, depending on which is shorter.

#include <stdio.h>
main(){
   
    printf("%g", 123456.123456);
    printf("\n%g", 6.1);
}
123456
      6.1

Printing floating-point numbers with floating-point conversion specifiers

#include <stdio.h>
int main()
{ 
   printf( "%e\n", 1234567.89 );
   printf( "%e\n", +1234567.89 );
   printf( "%e\n", -1234567.89 );
   printf( "%E\n", 1234567.89 );
   printf( "%f\n", 1234567.89 );
   printf( "%g\n", 1234567.89 );
   printf( "%G\n", 1234567.89 );
   return 0;
}
1.234568e+06
1.234568e+06
-1.234568e+06
1.234568E+06
1234567.890000
1.23457e+06
1.23457E+06

To create precision with floating-point numbers

%.2f displays only two zeroes after the decimal point.


#include <stdio.h>
main(){
    printf("%.1f", 3.123456);
    printf("\n%.2f", 3.123456);
    printf("\n%.3f", 3.123456);
    printf("\n%.4f", 3.123456);
    printf("\n%.5f", 3.123456);
    printf("\n%.6f", 3.123456);
}
3.1
      3.12
      3.123
      3.1235
      3.12346
      3.123456

use the %E in printf() to display scientific-notation numbers

#include <stdio.h>
 
int main()
{
    float lightyear = 5.878E12;
    float jupiter = 483400000;
    float distance;
 
    distance = jupiter/lightyear;
 
    printf("Jupiter is %E light years from the sun.\n",distance);
 
    return(0);
}
Jupiter is 8.223886E-005 light years from the sun.