我确定我做错了什么,但我就是想不通。我已经创建了一个具有整数数据成员的对象,并且我想让一个成员函数将其成员的商作为浮点值返回,它确实这样做了。然后它附加一些额外的东西。输出在程序下方,应按原样运行。
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Rational
{
public:
explicit Rational(int = 0, int = 1);
double getRationalAsDouble() const;
private:
int numerator;
int denominator;
};
Rational::Rational(int numerator, int denominator)
{
if (denominator == 0)
this->denominator = 1;
else
this->denominator = denominator;
this->numerator = numerator;
}
// ******* Problem Function *********
double Rational::getRationalAsDouble() const
{
double a = 0.0, b = 0.0;
a = static_cast<double>(numerator);
b = static_cast<double>(denominator);
cout << endl << "a = " << a;
cout << endl << "b = " << b;
cout << endl << "a/b = " << (a/b);
}
// ******** End Problem Function ********
int main()
{
{ //Create a new Scope so that I can view Destructor Message, not used here
Rational c(2, 6);
int data = 10;
cout << c.getRationalAsDouble(); // prints rational object c as double, but not really
cout << "\n\n";
} // End of Scope
return 0;
} // end main
这是输出:
a = 2
b = 6
a/b = 0.3333332.31196e-317
我一直在尝试,如果我将函数更改为在其中包含任何常规除法,它就可以正常工作。真正有趣的是,如果我在 cout << endl << "a/b = "<< (a/b); 行之后添加任何输出,该输出是在行的 (a/b) 部分之前处理。任何帮助将不胜感激!提前感谢您的宝贵时间。
解决方案: 该函数没有返回任何东西。当代码更改为:
double Rational::getRationalAsDouble()
{
return static_cast<double>(numerator)/denominator;
}
它按预期工作。谢谢 tc.
最佳答案
三个问题:
- 您想在行的结尾 打印endl,而不是“开头”。您的代码最终会(有效地)执行
cout << endl << "a/b = " << (a/b); ... cout << c.getRationalAsDouble(); cout << "\n\n";
打印两个 double0.333333
和2.31196e-317
彼此相邻,没有空间。 - 你想要(也许)
cout << "\n" << endl
而不是cout << "\n\n"
.endl
导致流被冲洗;普通的“\n”可能不会。 -
Rational::getRationalAsDouble()
没有返回值。听取您的编译器警告。
修复看起来像
double Rational::getRationalAsDouble() const
{
double a = 0.0, b = 0.0;
a = static_cast<double>(numerator);
b = static_cast<double>(denominator);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "a/b = " << (a/b) << endl;
return a/b;
}
关于c++ - 将对象 int 数据成员转换为 float 并除法将奇怪的数据 cout 附加到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22889533/