【问题标题】:C++ : How to use a pointer in an if statement conditionC++:如何在 if 语句条件中使用指针
【发布时间】:2018-01-12 03:02:51
【问题描述】:

我正在编写一个程序,它接收 3 个用户输入的二次方程值,进行一些计算,并返回二次方程的根数。

当我打印 *(point) 时,它会从函数中给我正确的值。

但是,当我在 If 条件中使用 *(point) 时,它似乎并没有按我想要的方式工作 - 我相信 *(point) 总是某个正数,因此为什么它总是执行那个特定的 if 条件.

用户值:a = 9b = -12c = 4 应该打印出来这个二次有 1 个根。 并且值:a = 2b = 16c = 33 应该打印出 这个二次方有 2 个根。 但程序总是打印出 这个二次方有 0 个根。 无论输入什么值。

这是我的代码:

#include "stdafx.h"
#include <iostream>

using namespace std;

float *quadratic(float a1[]);

int main()
{

    float a1[3] = {};
    float *point;

    cout << "Enter a: ";
    cin >> a1[0];
    cout << "\nEnter b: ";
    cin >> a1[1];
    cout << "\nEnter c: ";
    cin >> a1[2];

    point = quadratic(a1);

    cout << endl << "d = " << *(point) << endl; 

    if (*(point) < 0) {
        cout << "\nThis quadratic has 2 roots.\n";
    }
    else if (*(point) > 0) {
        cout << "\nThis quadratic has 0 roots.\n";
    }
    else { //else if *(point) is equal to 0
        cout << "\nThis quadratic has 1 root.\n";
    }

    return 0;
}

float *quadratic(float a1[]) {

    float d;
    d = (a1[1] * a1[1]) - (4 * a1[0] * a1[2]);

    float xyz[1] = { d };
    return xyz;

}

【问题讨论】:

  • 你不应该在这里使用指针
  • 您不能从函数返回指向本地数组的指针。函数退出时数组被销毁。
  • 您正在返回一个悬空指针。使用std::vector(可复制)而不是原始数组(不可复制)。对原始指针和原始数组等说不。
  • 为什么不只返回一个双倍

标签: c++ pointers if-statement


【解决方案1】:

您的函数quadratic 返回一个指向本地数组的指针。函数返回后,该数组不再存在。那么这个指针就是一个悬空指针,一个指向内存中某个地方的指针,这个地方曾经保存过一个对象,但现在可能保存着任何东西或者只是垃圾。

由于quadratic 尝试返回的数组始终是一个值,因此无需返回数组。只需返回该值。

您甚至不需要处理多项式系数的数组,因为它们总是三个,但如果数组看起来比单独的 abc 变量更好,那么只需使用 @987654327 @,例如像这样:

#include <iostream>
#include <array>
#include <vector>
using namespace std;

using Float = double;
auto square_of( Float const v ) -> Float { return v*v; }

auto determinant( array<Float, 3> const& a )
    -> Float
{
    return square_of( a[1] ) - 4*a[0]*a[2];
}

auto main()
    -> int
{
    array<Float, 3> a;
    cout << "Enter A: "; cin >> a[0];
    cout << "Enter B: ";  cin >> a[1];
    cout << "Enter C: ";  cin >> a[2];

    Float const d = determinant( a );

    cout << "d = " << d << endl; 
    if( d < 0 )
    {
        cout << "This quadratic has 2 roots." << endl;
    }
    else if( d > 0 )
    {
        cout << "This quadratic has 0 roots." << endl;
    }
    else // d == 0
    {
        cout << "This quadratic has 1 root.";
    }
}

上面的代码等同于我认为你的代码的意图。

不过,我会先查看formula for roots of quadratic equations,并测试程序,然后再交出一些东西。

【讨论】:

    猜你喜欢
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 2016-02-28
    • 2021-08-03
    • 2016-05-28
    相关资源
    最近更新 更多