为什么这段代码产生奇怪的,意外的输出?

时间:2014-07-26 23:57:22

标签: c++ pointers double cout

为什么我没有得到正确的结果?

我没有得到正确的px输出,虽然我把它命名为double我得到了一些奇怪的数字文本mashup因此。

#include <iostream>
using namespace std;

int main(){
double a = 0; double b = 0; double c = 0; double x = 0;
cout << "Welcome to Lytis! \nPlease enter a:";
cin >> a;
cout << "Please enter b:";
cin >> b;
cout << "Please enter c:";
cin >> c;
if (a != 0){
    double d = (b*b) - (4 * a * c);
}
f (d == 0){
        double x =  -(b) / (2 * a);
        double *px = &x;
        cout << "The only solution is x=" << px;
        cin.get();
    }

我错过了什么?

2 个答案:

答案 0 :(得分:2)

1)您的代码无法编译(例如d未声明)

2)&#34;数字文本网格&#34;是您要打印的地址x (指针)。

使用解除引用运算符*获取指向的值:

cout << "The only solution is x=" << *px;
                                    ^^^
                                    Here

3)您应该检查cin的返回值,以防止错误输入。

4) "Lytis" means "Sex" in Lithuanian.

答案 1 :(得分:1)

px的类型为double *,因此输出它会打印出一个内存位置(通常以十六进制表示,即0-9 A-F)。

赋值double *px = &x是合法的,因为它正在为指针分配引用(内存位置),但是当您输出带有cout的指针时,它将显示其位置。

也许试试:

cout << "The only so....." << *px;
相关问题