c语言中warning C4305: 'initializing' : truncation from 'const double' to 'float'

# include<stdio.h>
# include<string.h>
# define FORMAT "%d\n%s\n%f\n%f\n%f\n"
struct student
{
int num;
char name[20];
float score[3];
}stu={12345,"lili",67.5,89,78.6};//就是这个地方出错了,说是不能直接将double传给float,这是为什么?
void main()
{
void print(struct student *);
print(&stu);
}
void print(struct student *p)
{
printf(FORMAT,p->num,p->name,p->score[0],p->score[1],p->score[2]);
printf("\n");
}
我将78.6改成78.5的时候就不会警告,但是改成其他的小数就又错了,再者,在后面加上f的话,打印出来的却是78.599998这是个什么情况?我都指定类型了怎么还错误啊?

这就涉及计算机组成原理了,计算机存储方式为二进制,占4字节。转化为十进制后自然有的数字表达不了。遇到这种情况后一般是
if(abs(x-78.6f)<0.01) balabala
另外,一般不推荐用float,精度差是一方面,另一方面是在c++中小数(如0.1)是默认为double的,你不可以这样子:float x=78.6;编译会报错,warning C4305: 'initializing' : truncation from 'const double ' to 'float '
原因:

在C/C++中,VC++和LINUX都是,上述语句等号右边78.6,我们以为它是个float,但是编译器却把它认为是个double(因为小数默认是double),所以要报这个warning。

把高精度的变量赋值给低精度的变量,可能会有精度丢失。所以得到一个类似值78.599998

通常的做法,经常使用double,而不喜欢使用float。
温馨提示:答案为网友推荐,仅供参考
相似回答