首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试调试和更正函数

尝试调试和更正函数
EN

Stack Overflow用户
提问于 2013-10-27 06:32:33
回答 2查看 82关注 0票数 1
代码语言:javascript
复制
#include <iostream>
#include <string>
using namespace std;

// Declaration of the function indexvalue()
int *maxArr(int [], const int);

// Another function used to print out an error message
    void
    problem(string str) {
        cout << str << endl;
        exit(1);
}

const int Size = 10;

int main() 
{
        int a[Size] = {23, 45, 12, 76, 9, 131, 10, 8, 23, 4};
    int *b, i;

        string error1("Problem with maxArr(), wrong subscript"); 
        string error2("Problem with maxArr(), output should be NULL");

// Call the function multiple times with different input
// Note the use of pointer arithmetic
        if (maxArr(a,Size)!= a+5)   problem(error1);
        if (maxArr(a,Size-5)!= a+3) problem(error1);
        if (maxArr(a+6,4)!= a+8)    problem(error1);
        if (maxArr(a,0)!= NULL)     problem(error2);
// The function passed all the tests

        cout << "The function passed all the tests in this program\n" << endl;
        exit(0);
}

int *maxArr(int arr[], int size){
   int max = 0;
   int index = 0;

   if ( size < 0)
    return NULL;

   for (int i = 0; i < size; i++) {
    if (arr[i] > max )
    {
       max = arr[i];
       index = i;
    }
        return arr + i;
   }           
}

maxArr()的规范

该函数接受整数数组和元素数量作为参数。此函数返回int的地址,该地址指向数组的最大值。

我试图找出maxArr()函数的错误所在,到目前为止,我唯一更正的是将if ( <= < 0)更改为if(size <= 0)为了处理null的情况,我不知道如何更正该函数以解决error1消息。任何帮助都将不胜感激。

EN

回答 2

Stack Overflow用户

发布于 2013-10-27 06:39:10

您将从函数maxArr中的for循环内部返回。它总是会在第一次迭代中返回。另外,您应该返回arr+index而不是arr+i

代码语言:javascript
复制
for (int i = 0; i < size; i++) 
{
    if (arr[i] > max )
    {
       max = arr[i];
       index = i;
    }
    //return arr + i;
    // ^^^^ Wrong
} 
return arr+index; //return from here

检查返回NULL的操作将会失败,这是您当前的情况。您应该像这样检查:

代码语言:javascript
复制
if ( size <= 0)
    return NULL;
票数 0
EN

Stack Overflow用户

发布于 2013-10-27 06:43:43

这里有一个括号问题:

代码语言:javascript
复制
   for (int i = 0; i < size; i++) {
    if (arr[i] > max )
    {
       max = arr[i];
       index = i;
    }
        return arr + i;
   }

您的返回位于for循环中,因此您将在循环的第一次迭代中返回。

如果不使用索引,您可能希望将return语句移出主循环并返回arr + index;

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19612613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档