【问题标题】:C++ function outputC++ 函数输出
【发布时间】:2017-03-22 09:26:11
【问题描述】:

我正在尝试在此程序中输出计算得出的三角形面积,但是当我尝试从函数中输出面积时,我得到的是字母和数字的混合而不是答案,如果有人能指出我在做什么错了,不胜感激。

我已经厌倦了 tArea(area) 但它给出了不同的错误。

【问题讨论】:

  • cout << "the area is" << tArea; 你没有调用你的函数

标签: c++ function output


【解决方案1】:

您没有调用该函数。当您使用不带括号的 tArea 名称时,C++ 将给您函数的地址而不是调用它,并且这将以十六进制格式打印。

此外,您可以使用局部变量而不是使用参数进行工作计算:

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <cmath>
using namespace std;

float tArea(float a, float b, float c);

int main()
{
    float a, b, c;

    cout << "Enter side 1: ";
    cin >> a;
    cout << "Enter side 2: ";
    cin >> b;
    cout << "Enter side 3: ";
    cin >> c;

    cout << "the area is" << tArea(a, b, c);

    return 0;
}

float tArea(float a, float b, float c)
{
    float s = (a + b + c) / 2;
    float area = sqrt(s*(s - a)*(s - b)*(s - c));
    return area;

}

【讨论】:

    【解决方案2】:

    当你这样做时

    cout << "the area is" << tArea;
    

    您正在向标准输出发送数据。您可以将其视为将数据打印到控制台,因为这是标准输出通常所在的位置。

    在这种情况下,tArea 只是一个引用,它告诉计算机在哪里可以找到实际的tArea() 功能代码。

    所以你实际上只是打印 reference tArea 这是一个地址。该地址是一个数字,但 iostream cout 并不真正知道这意味着什么。它试图尽其所能地解释它,结果却全是字母和数字的乱码。

    您要做的是调用您的区域函数并打印返回的结果。为此,您必须在函数调用的末尾添加括号。

    如果你有一个不带参数的区域函数,那么你可以这样调用它tArea();

    但是在您的代码中,函数签名如下

    float tArea(float a, float b, float c, float s, float area)
    

    这意味着为了让您的函数将区域作为浮点数返回,您必须传入 5 个参数。所有 5 个参数都必须是浮点数。

    对你来说有效的电话是这样的

    tArea(2.0, 2.1, 1.8, 3.0, 4.0);
    

    通过改变这一行

    cout << "the area is" << tArea;
    

    到这里

    cout << "the area is" << tArea(a, b, c, 1.0, 1.0);
    

    你可以解决你的问题。

    我确实鼓励您更进一步,并更改以下与您的确切问题无关的行。 改变

    float tArea(float a, float b, float c, float s, float area)
    {
        s = (a + b + c) / 2;
        area = sqrt(s*(s - a)*(s - b)*(s - c));
        return area;
    
    }
    

    float tArea(float a, float b, float c)
    {
        float s = (a + b + c) / 2;
        float area = sqrt(s*(s - a)*(s - b)*(s - c));
        return area;
    }
    

    然后这样称呼它

    cout << "the area is" << tArea(a, b, c);
    

    这更好,因为它从函数签名中删除了 sarea。由于在 area 函数内部进行计算之前不需要它们,并且它们会在函数内部立即重写,因此我们不在乎它们之前的值是什么。这就是为什么我向您展示它们都可以作为 1.0.0 传入的原因。实际上,它们可以是任何浮点数,这无关紧要,因为它们会立即被覆盖。

    正如 IanM_Matrix1 所建议的那样,

    sarea 应该是仅特定于区域函数的 范围 的局部变量。这样做可以让这些临时变量更早地被销毁,从而释放内存。这样做是一种更好的做法。

    【讨论】:

      猜你喜欢
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 2010-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多