注册 登录
编程论坛 C++教室

[求助]这个为什么错了?

dengtc 发布于 2007-05-23 18:22, 618 次点击
求助]这个为什么错了?
我用的是VC++2005
#include <iostream>
using namespace std;
struct inflatable
{
char name[20];
float volume;
double price;
};
int main()
{
inflatable guest=
{
"Glorious Gloria",
?1.88,
29.99
};
inflatable pal=
{
"Audacious Arthur",
?3.12,
32.99
};
cout<<"Expand your guest list with "<<guest.name<<" and "<<pal.name<<"!\n";
cout<<"You can have both for $"<<guest.price+pal.price<<"!\n";
return 0;
}
警告 1 warning C4305: “初始化”: 从“double”到“float”截断 e:\microsoft visual studio 2005 简体中文专业版\vc++2005\项目\4.11\4.11\structur.cpp 14
警告 2 warning C4305: “初始化”: 从“double”到“float”截断 e:\microsoft visual studio 2005 简体中文专业版\vc++2005\项目\4.11\4.11\structur.cpp 20
请各位大哥指点指点!!

#include <iostream>
using namespace std;
struct inflatable
{
char name[20];
float volume;
double price;
};
int main()
{
inflatable pal[2]=
{
{"Glorious Gloria",1.88,29.99},
{"Audacious Arthur",3.12,32.99}
};
cout<<"Expand your guest list with "<<pal[0].name<<" and "<<pal[1].name<<"!\n";
cout<<"You can have both for $"<<pal[0].price+pal[1].price<<"!\n";
return 0;
}
这个和上面出来的结果一样,哪个更好些?

我用的是VC++2005

请各位大哥指点指点!!

#include <iostream>
using namespace std;
struct inflatable
{
char name[20];
float volume;
double price;
};
int main()
{
inflatable pal[2]=
{
{"Glorious Gloria",1.88,29.99},
{"Audacious Arthur",3.12,32.99}
};
cout<<"Expand your guest list with "<<pal[0].name<<" and "<<pal[1].name<<"!\n";
cout<<"You can have both for $"<<pal[0].price+pal[1].price<<"!\n";
return 0;
}
这个和上面出来的结果一样,哪个更好些?不过2个程序都出现2个警告!!警告如下:
警告 1 warning C4305: “初始化”: 从“double”到“float”截断 e:\microsoft visual studio 2005 简体中文专业版\vc++2005\项目\4.11-\4.11-\-.cpp 13
警告 2 warning C4305: “初始化”: 从“double”到“float”截断 e:\microsoft visual studio 2005 简体中文专业版\vc++2005\项目\4.11-\4.11-\-.cpp 14

[此贴子已经被作者于2007-5-23 18:36:48编辑过]

6 回复
#2
lovehug2007-05-23 18:26

我用Visual C++ 6.0运行出来就是对的!

#3
dengtc2007-05-23 18:38
那是不是我的VC++2005有问题呢?总是出现2个警告!!!
#4
aipb20072007-05-23 18:50
以下是引用dengtc在2007-5-23 18:38:07的发言:
那是不是我的VC++2005有问题呢?总是出现2个警告!!!

没有问题,这正说明vc++2005比vc++6.0编译更严密啊!

浮点数字面值常量,也就是你直接打一个浮点数10.1,编译器会把它识别成const double类型,所以这里它提示你从double赋值到float截断。

解决办法:1. {"Glorious Gloria",1.88f,29.99},
{"Audacious Arthur",3.12f,32.99}

2.double volume;


[此贴子已经被作者于2007-5-23 19:53:07编辑过]

#5
dengtc2007-05-23 20:30
哦!
谢谢!aipb2007!
那是用第一种方法好还是第二种好?
#6
aipb20072007-05-23 20:55
回复:(dengtc)哦!谢谢!aipb2007!那是用第一种方...
根据你的需要!你觉得float已经足够了,那就第一种吧!

不过我推荐第2种,还有,以后用浮点数最好都用double(不是绝对哦,我指某些简单的程序),这样一般不会出现丢失精度引起的错误(这种错误,有时不易发觉)。

#7
dengtc2007-05-24 16:44
哦!
谢谢!aipb2007
1