0
#include <iostream>
#include <iomanip>
using namespace std;

class Rectangle 
{
float x, y;
public:
void value (float,float);
float area () {return (x*y);}
};

void Rectangle::value (float a,float b) 
{
x = a;
y = b;
}

class Circle 
{
float x;
public:
void value (float);
float area () {return (3.14*x*x);}
};

void Circle::value (float a) 
{
x = a;
}

int main () 
{
float q,a,b;
char reply;

cout << "\t\tArea Calculator";
do
{
cout << "\n\nPlease select from the following: ";
cout << "\n1. Rectangle";
cout << "\n2. Cirlce";
cout << "\n3. Exit";
cout << "\n\n";
cin >> q;
if (q==3)
break;

if (q==1)
{
system("cls");
Rectangle rect;
cout << "\nPlease enter length: ";
cin >> a;
cout << "\nPlease enter width: ";
cin >> b;
cout << "\nArea: " << rect.area();
cin.get();
cout << "\n\nDo you want to continue y/n: ";
cin >> reply;

    if (toupper(reply) == 'N') 
        {
        cout << "\n\n";
        cout << "Goodbye!";
        break;
        }
}

if (q==2)
{
system("cls");
Circle circ;
cout << "\nPlease enter radius: ";
cin >> a;
cout << "\nArea: " << circ.area();
cin.get();
cout << "\n\nDo you want to continue y/n: ";
cin >> reply;

    if (toupper(reply) == 'N') 
        {
        cout << "\n\n";
        cout << "Goodbye!";
        break;
        }
} 

}   while (toupper(reply!='Y'));
{
cout << "\n\n";
system("pause");
}
}

上面的代码调试时出现以下警告:

“警告 C4244:'return':从 double 转换为 float,可能丢失数据”

...我很确定这是代码运行时计算错误的原因(例如,它返回 5x5 正方形的面积为 1.15292e+016) - 请任何人解释解决此问题的正确方法,我似乎无法理解它:(

4

2 回答 2

1

错误的结果不是 double 到 float 转换的结果,而是未初始化 Rectangle/Circle 对象的维度成员的结果。您需要在读取用户的值后调用 rect.value(a,b) 。不这样做会使对象的 x 和 y 成员未初始化,因此包含一些任意值 - 导致计算结果错误。为圆调用 circ.value(a) 也是如此。

cout << "\nPlease enter length: ";
cin >> a;
cout << "\nPlease enter width: ";
cin >> b;
rect.value(a,b);
cout << "\nArea: " << rect.area();

double 到 float 转换的警告可能是“cin >> b”样式行的结果。cin 流 >> 运算符处理读取双精度,而不是浮点数。当您尝试从 cin 读取到浮点数时,首先会得到一个双精度值,然后将其隐式转换为浮点数。由于 float 的精度低于 double,编译器会警告您这样做可能会丢失精度。假设浮点精度就足够了——这没有问题。您可以简单地通过声明类和变量来使用双精度而不是浮点数来解决这个问题。

于 2013-09-22T09:39:01.827 回答
0

您没有初始化类的数据成员

rect.area();并且circ.area();正在计算一些垃圾值的面积

使用构造函数:

Rectangle(float a, float b):x(a),y(b){}

Circle(float a):x(a){}

然后

cin >> a;
cin >> b;
Rectangle rect(a,b);
rect.area();

cin >> a;
Circle circ(a);
circ.area();
于 2013-09-22T05:28:45.223 回答