C语言,float类型数据小于1时,用%.2f输出结果是0.00,怎样让输出结果不四舍五入

C语言,float类型数据小于1时,用%.2f输出结果是0.00,怎样让输出结果不四舍五入

问题描述:

大家好,学习C语言过程中,遇到一个问题,麻烦解答下,谢谢:
程序如下:
#include<stdio.h>
int main(void)
{
float download_speed, file_size, download_time;

download_time=file_size*8/download_speed;

printf("Please enter what's the size(MB) of the files and the download speed(MB/s).\n");
scanf("%f%f",&file_size,&download_speed);
printf("At %.2f megabits per second, a file of %.2f megabytes downloads in %.2f seconds.\n",download_speed,file_size,download_time);

return 0;

}

这里输入 file_size=2.2136 ; download_speed=18.12322 ;

按照这样计算, download_time=0.977133, 保留2位数 应该是0.98 。 但是 程序运行的结果是 0.00 。如下:

img

请问 这是由于在输出时自动做了四舍五入吗? 怎样才能让程序输出 0.98 呢? 或者 不四舍五入 直接输出 0.97?
谢谢!

你这个计算表达式放在最上面,先计算再输入,肯定是默认的0撒,至于说0.98和0.97的问题,你用格式化字符串也就是.2f是会被默认四舍五入的,你可以先乘以100再除以100,就可以去除多余的尾数,不会造成四舍五入