有关c的简单问题

来源:百度知道 编辑:UC知道 时间:2024/06/25 16:43:57
#define W 3.14
#include<stdio.h>
main()
{float r=1.5,h=3,c,s;
c=W*2*r;s=W*r*r*2+r*h;
printf("c=%f,s=%f",c,s);
}
在vc6编译
--------------------Configuration: noname - Win32 Debug--------------------
Compiling...
2.c
D:\turboc2\2.c(5) : warning C4244: '=' : conversion from 'double ' to 'float ', possible loss of data
D:\turboc2\2.c(5) : warning C4244: '=' : conversion from 'double ' to 'float ', possible loss of data

2.obj - 0 error(s), 2 warning(s)
两个warning而在turboc2则没问题,能给我讲讲吗?

W 宏替换后 3.14 为double型常量
c=3.14*2*r;
表达式 3.14*2*r 自动类型转换仍为 double 型
而 C 为 float 类型
VC6编译时, 将 double 类型的值赋给 float 类型的变量会 warning
而TC赋值是同样自动类型转换而不给warning

#include<stdio.h>
main()
{float r=1.5,h=3,c,s,w=3.14;
c=w*2*r;s=w*r*r*2+r*h;
printf("c=%f,s=%f",c,s);
}
这样就行了

我不知道你的编译器有什么问题。我把程序复制到我的VC++上运行过之后,没有错误,也没有警告。不过float r=1.5,h=3,c,s; 这句话中VC++中默认1.5是double型,所以可以的话,写成这样float r=1.5f,h=3f,c,s;