【问题标题】:how do i return multiple values from a function in c++ [duplicate]我如何从c ++中的函数返回多个值[重复]
【发布时间】:2022-01-20 09:42:33
【问题描述】:

我想从一个布尔函数返回两个浮点变量,虽然我不知道该怎么做。我应该在main中写什么?这是我的代码。

bool triwnymo(int a, int b, int c, float& x1, float& x2){
    
    int d;
    d=diak(a,b,c);
    if(d>0){
        x1=(-b+sqrt(d))/(2*a);
        x2=(-b-sqrt(d))/(2*a);
        return x1,x2;
        return true;
    }else if(d==0){
        x1=-b/(2*a);
        x2=x1;
        return x1,x2;
        return true;
    }else{
        return false;
    }
}

【问题讨论】:

  • 您有几个选择 - 也许这可以回答您的问题:stackoverflow.com/questions/321068/… ?
  • 这可能对你来说很有趣:isocpp.github.io/CppCoreGuidelines/…
  • 您确定要返回这些值吗?从声明看来,您希望返回一个bool 并覆盖x1x2 的值。我的意思是,如果不将它们用作外参数,为什么要通过非常量引用传递它们?
  • 当函数返回时,值在您作为x1x2 传递的变量中。 (我怀疑有人给了你原型,并且认为参考参数并不重要。)
  • 声明 return x1,x2; 不会做你想做的事。相反,它将忽略 x1 并返回如果将 x2 转换为 bool 会得到的结果。

标签: c++ function variables return-value


【解决方案1】:

您可以使用自定义数据结构返回任意数量的值:

struct triwnymo_result_type {
     float root1 = 0.0;
     float root2 = 0.0;
     bool has_solution = false;
};

triwnymo_result_type triwnymo(int a, int b, int c){        
    int d = diak(a,b,c);
    if(d>0) {
        return  {(-b+sqrt(d))/(2*a), (-b-sqrt(d))/(2*a), true};
    } else if(d==0) {
        int x=-b/(2*a);
        return {x,x,true};
    } else {
        return {0.0,0.0,false};
    }
}

请注意,return x1,x2; 使用的是逗号运算符。逗号运算符计算两个操作数,丢弃第一个并得出后者的值。那不是你想要的。在你已经从函数返回之后,return true; 也永远不会到达。一个函数只能返回一次。

我不想改变太多,但是你真的不需要区分d>0d==0,因为当d==0然后-b+sqrt(d) == -b-sqrt(d) == -b

【讨论】:

  • 我特别赞成使用这个解决方案,如果你给结构中的成员起好名字,它可以保持代码的干净和可读性(pair 和 tuple 不适合我)。在这种情况下,我会调用成员:root_1、root_2 和 has_solution
【解决方案2】:
#include <tuple>
// bad answer.
//// by pair
//std::pair<bool, float> triwnymo(...) {...}

// 1. by tuple
std::tuple<bool, float, float> triwnymo(...) {...}

// 2. by class or struct
struct data { bool b; float f1; float f2; };
data triwnymo(...) {...}

// 3. by reference or pointer
bool triwnymo(..., float& float_out1, float& float_out2) {...}

// other way
float f1, f2;
bool triwnymo(...) {...; f1 = ?; f2 = ?; }

【讨论】:

  • 该代码返回 one 浮点值。该问题询问有关返回 两个 浮点值的问题。如果还要返回 bool 值,则排除使用 std::pair 的可能性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-19
  • 2015-03-04
  • 2021-01-29
  • 2021-12-21
相关资源
最近更新 更多