【问题标题】:Using a return value of one function in another (C)在另一个函数中使用一个函数的返回值 (C)
【发布时间】:2016-06-28 20:39:24
【问题描述】:

我正在尝试解决这个问题,但我找不到任何关于 C 语言的答案。问题是,当我尝试在另一个函数中使用返回值时,该值没有通过,并且在打印时显示为“0”。

int getFinanceAmt(float Cost, float Deposit){
    float Financing;
    Financing = Cost - Deposit;
        printf("%f\n", Financing);

return Financing;}

因此,我们的目标是利用该返回值并代入该函数内部的方程式:

int getInterest(float Financing, float interestRate){
    float interest;
    interest = Financing * interestRate;
        printf("%f\n", interest);

return interest;}

我还必须在另一个函数中执行此操作,这也是“interestRate”的来源。这也在另一个功能中。我需要某种指针对吗?

【问题讨论】:

  • 贴出“在另一个函数中使用返回值”的代码。这两个函数都不会互相调用。或显示“另一个功能”。或者可能是打印的代码。
  • 从应该返回int的函数getFinanceAmt()返回float Financing是什么意思?
  • 如果代码需要将float转换为最接近的整数值,不要使用(int),而是使用roundf(x)

标签: c function return


【解决方案1】:

您的返回类型不匹配。将您的返回类型更改为float,它应该可以正常运行

【讨论】:

  • 已更改,但仍打印 0。
【解决方案2】:

首先,在 getFinanceAmt 中,看起来函数被声明为返回一个 int,但后来又返回一个 float。所以首先将 getFinanceAmt 更新为:

float getFinanceAmt(float cost, float deposit)
{
    float financing;
    financing = cost - deposit;
        printf("%f\n", financing);

    return financing;
}

另一个函数也发生了同样的事情。但更重要的是,您需要按名称实际调用第一个函数,并为其提供我们上面声明的所需参数。我建议只在 getInterest 中引入三个参数,然后在内部使用它们来调用 getFinanceAmt。

float getInterest(float cost, float deposit, float interestRate)
{
    float interest;
    interest = getFinanceAmt(cost, deposit) * interestRate;
        printf("%f\n", interest);

    return interest;
}

【讨论】:

    【解决方案3】:

    解决了两个函数返回类型错误的问题,您可以执行以下操作来使用从一个函数返回的值作为另一个函数的参数:

    float getFinanceAmt(float Cost, float Deposit)
    {
        return Cost - Deposit;
    }
    
    float getInterest(float Financing, float interestRate)
    {
        return Financing * interestRate;
    }
    
    void foo()
    {
        float cost, deposit, rate;
    
        /* more code here, which initializes the above variables */
    
        printf("Interest is %f\n", getInterest(getFinanceAmt(cost, deposit), rate));
    }
    

    【讨论】:

      【解决方案4】:

      不,正如我所见,您在这里不需要 指针。在您的情况下,您的意图和您的代码不匹配。

      Financinginterest 的类型为 float,但返回它们的函数的返回类型为 int。您可能希望将函数返回类型更改为 float 以使其兼容。

      【讨论】:

      • 令人惊讶的是我完全忽略了这一点。已更改但仍打印 0。
      • @KyleSteward 你如何打印返回值? %f,确定吗?
      • 代码不应该打印,但我打印是为了测试,但是是的,我使用的是 '%f'。
      • @KyleSteward 你介意创建一个MCVE吗?你在哪里看到 0?
      • Doug 似乎通过简单地调用函数并调整参数来修复它。我认为这是方法,但不知道正确的语法方法。但感谢您的帮助并指出 in/float 错误!欣赏!
      猜你喜欢
      • 2010-09-15
      • 1970-01-01
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多