繁体   English   中英

内置函数将返回正数之和。

[英]inbuilt Function that will return Sum of positive number.?

我有一个数组,我想要stl函数,该函数可以返回正数之和和负数之和。

#include <iostream>    
#include <functional>   
#include <numeric>     

int myfunction (int x, int y) 
{
    if(y>0){
        return x+y;
    }
}



int main () {
int init = 0;
int numbers[] = {5,10,20,-34,56,-67,-32,16};


std::cout << "using custom function: ";
std::cout << std::accumulate (numbers, numbers+8, init, myfunction);
std::cout << '\n';


}

输出是即将到来的垃圾值。

使用自定义功能:4196215

您的“输出即将到来的垃圾值”的原因是,当y <= 0您将返回一些垃圾值(即,没有return语句)。

int myfunction (int x, int y) 
{
    if(y>0){
        return x+y;
    }

    // <<== you need to return something here, too
}

我会说在这种情况下return x ,但不适用于第一个元素为<= 0数组

您可能正在寻找符合以下条件的东西:

int myfunction (int x, int y) 
{
  return x + std::max(y, 0);
}

如果一个函数的返回类型与签名中的void不同,则无论执行过程中采用哪种路径, 需要确保该函数始终 (除非发生一些特殊事件)返回某个值。

您的函数无法执行此操作,因为当y<=0您什么也不返回。

您可以执行以下操作来修复它:

int myfunction (int x, int y) 
{
    if(y>0)
        return x+y;
    return x;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM