为什么这段代码不能返回值为 505.5 的 bpEffect 变量? [英] Why can this code not return the bpEffect variable with the value 505.5?
本文介绍了为什么这段代码不能返回值为 505.5 的 bpEffect 变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码的预期结果应该是 505.5,但它返回 3.97541e+70.为什么会这样?如何解决?
The expected result from the following code should be 505.5, but instead it returns 3.97541e+70. Why is this the case and how can the problem be solved ?
#include <iostream>
#include <string>
using namespace std;
class Position {
public:
Position(int s, double p, string n) {
shares = s;
price = p;
name = n;
}
double getBpEffect() {
return bpEffect;
}
private:
string name;
int shares;
double price;
double bpEffect = (shares*price) / 2;
};
int main() {
Position xyz = Position(100, 10.11, "xyz");
double buyingPower = xyz.getBpEffect();
cout << buyingPower;
system("pause");
return 0;
}
推荐答案
double bpEffect = (shares*price)/2;
在你的构造函数主体之前运行使用 shares
和 price
中未定义的值.您需要在初始化其他变量后计算 bpEffect
.
double bpEffect = (shares*price) / 2;
is run before the body of your constructor using the undefined values in shares
and price
. You need to calculate bpEffect
after you have initialized the other variables.
这篇关于为什么这段代码不能返回值为 505.5 的 bpEffect 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文