问题如图:
然后我使用了一下两段相同的代码,只是对变量的数据类型定义不同:
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
float celsius,fahr;
printf("celsius = ");
scanf("%f",&celsius);
fahr=(9/5.0)*celsius+32;
printf("fahr = %f",fahr);
return 0;
}
//结果:98.959999
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
double celsius,fahr;
printf("celsius = ");
scanf("%lf",&celsius);
fahr=(9/5.0)*celsius+32;
printf("fahr = %lf",fahr);
return 0;
}
//结果:98.960000
实在想不通到底是哪个运算过程改变了结果,也想问一下是这里出问题的点是哪里?
拜托了,初学者小白学生党提问。
膜拜大佬,大佬的文章令我陶醉!
float型变量在参与计算时会自动转化为double型,但是你在输出时却有强制以%f型输出,故会丢失精度
参考:
A floating constant consists of an integer part, a decimal part, a fraction part, an e or E, an optionally signed integer exponent and an optional type suffix, one of f, F, l, or L. The integer and fraction parts both consist of a sequence of digits. Either the integer part, or the fraction part (not both) may be missing; either the decimal point or the e and the exponent (not both) may be missing. The type is determined by the suffix; F or f makes it float, L or l makes it long double, otherwise it is double.