C语言的基础输入输出

首先来整理一下各个数据类型的输入输出格式:

1.char  %c

2.int/short int  %d

3.long int   %ld

4.long long int  %lld

5.float  %f

6.fouble  %lf

然后,要如何保留位数呢?

%.xf,则表示float型的数保留小数点后x位。

%0xd,表示int型的数据保留x位整数,不足用0补充。

如果想要精确到小数点后某位,与数据类型有关。

如果直接在输出的时候控制位数,是不会精确的,如下:

 1 #include<stdio.h> 
 2 int main(){
 3     int a,b,c,d,sum;
 4     float ave;
 5     scanf("%d %d %d %d",&a,&b,&c,&d);
 6     sum=a+b+c+d;
 7     ave=sum/4;
 8     printf("Sum = %d; Average = %.1f",sum,ave);
 9     return 0;
10 }

输出的是10 2.0

如果想要精确,需要在运算的时候进行强制转型。

 1 #include<stdio.h> 
 2 int main(){
 3     int a,b,c,d,sum;
 4     float ave;
 5     scanf("%d %d %d %d",&a,&b,&c,&d);
 6     sum=a+b+c+d;
 7     ave=(float)sum/4;
 8     printf("Sum = %d; Average = %.1f",sum,ave);
 9     return 0;
10 }

如上输出位10 2.5

原文地址:https://www.cnblogs.com/luoyang0515/p/10219723.html