#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)-请有人解释正确的方法解决这个问题,我似乎无法解决这个问题 :(
最佳答案
错误的结果不是 double float 转换的结果,而是没有初始化矩形/圆形对象的维度成员的结果。 您需要在读取用户的值后调用 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 到浮点转换的警告可能是“cin >> b”样式行的结果。 cin 流 >> 运算符处理 double 读取,而不是 float 。 当您尝试将 cin 读入一个 float 时,您首先会得到一个 double 值,然后将其隐式转换为 float 。由于 float 的精度低于 double,编译器会警告您这样做可能会失去精度。假设浮点精度足够——这没有问题。您可以简单地通过声明类和变量使用 double 而不是 float 来解决这个问题。
关于C++ - 简单形状面积计算器返回错误计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18940597/