简体   繁体   English

将整数数组作为参数并返回数组中奇数之和的函数

[英]Function that takes an array of integers as a parameter and returns the sum of odd numbers in the array

I keep getting a error: "Run-Time Check Failure #3 - The variable 'x' is being used without being initialized." 我一直收到一个错误:“运行时检查失败#3 - 正在使用变量'x'而不进行初始化。”

I thought I initialized it with all the numbers I put in the array? 我以为我用数组中的所有数字初始化它?

#include <iostream>
using namespace std;

const int MAX = 10;

int odd(int sumOdd[])
{
int sum = 0;
for(int i = 0; i < MAX; i ++)
{
    if(sumOdd[i] % 2 != 0)
    sum+=sumOdd[i]; 
}
cout << "Sum of odd integers in the array: " << sum << endl;
return sum;

}

int main()
{
int x[MAX] = {13,14,8,7,45,89,22,18,6,10};

int returnArray(x[MAX]);

cout << "Sum of odd integers in the array" << endl;

system("pause");
return 0;
}

try to change: 试着改变:

 int returnArray(x[MAX]);

to

 int sum =  returnArray(x);
 cout << "Sum of odd integers in the array" << sum << endl;

returnArray returns sum . returnArray返回sum You can either use a temporary variable to hold the return value and print it out or directly use the return value as follows: 您可以使用临时变量来保存返回值并将其打印出来,也可以直接使用返回值,如下所示:

cout << "Sum of odd integers in the array" << returnArray(x) << endl;

When you call a function, simply use the function name and feed it with parameters, you don't need return type anymore ( int ) in this case. 当你调用一个函数时,只需使用函数名称并用参数提供它,在这种情况下你不再需要返回类型( int )。 You also directly use the array name x , not x[MAX] . 您也可以直接使用数组名称x ,而不是x[MAX]

int returnArray(x[MAX]); // in main

should be 应该

returnArray(x);

You've already declared the function as taking an array and returning an integer, so all you need to do is call the function with the array as the parameter. 您已经将该函数声明为采用数组并返回一个整数,因此您需要做的就是以数组作为参数调用该函数。

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

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