c++ - 为什么我的程序返回 5?

标签 c++ templates

我研究模板,我必须搜索最大元素 < 0。但函数返回 5。

#include <stdio.h>
#include <stdlib.h>
#include <ctime>

template <class Tdata, class Tnumber>
Tnumber min_max (Tdata arr[], Tnumber n)
{
    int i, p = 0,max_el=0;
    int a=0;
    Tdata arr_help[n];
    for (i=0; i<n; i++){
       if (0 > arr[i]){
            arr_help[a]=arr[i];
            printf("\n a = %i \n",a);
            a++;
        };
        printf("\narr_help = %i\n",arr_help[i]);
    }
    for (i=0;i<a;i++){
        printf("\n p = %i \n",p);
        if(arr_help[p]<arr_help[i+1]) p=i+1;
    }
    printf("\n p_bf_answr = %i \n",p);
    return p;
}

如果开始这段代码,最后的p是5

int main(){
    srand(time(0));
    int n=5, arr_int[n],i;
    //float arr_float[n];
    printf("\n");
    for (i=0;i<n;i++){
        arr_int[i]=(int)(-(rand()%11 +1));
    }
    printf("\nint_min = %i\n",(min_max(arr_int,n)));
   /* for (i=0;i<n;i++){
        arr_float[i]=(float)(-(rand()%10));
    }
    printf("\nfloat_min = %i\n",((int)min_max(arr_float,n)));*/
    return 0;
}

而且我不知道,我必须在这里写什么。这个网站需要哪些详细信息?

最佳答案

在最后一次循环

for (i=0;i<a;i++){
    printf("\n p = %i \n",p);
    if(arr_help[p]<arr_help[i+1]) p=i+1;
}

如果执行你比较

if(arr_help[p]<arr_help[a]) p=a;

但是 arr_help[a] 从未被设置并且可能超出了 arr_help 的数组范围。它可能包含任何东西,因此设置 p=a。

关于c++ - 为什么我的程序返回 5?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43831512/

相关文章:

c++ - 如何以编程方式更改布局中小部件的顺序?

c++ - Qt : send AT command to GPRS modem

c++ - 如何使用模板将结构存储在指针数组中

c++ - gcc 可以编译可变参数模板而 clang 不能

c++ - 推断参数包而不将其作为模板参数显式传递?

c++ - Portaudio C++ 绑定(bind) : symbol not found in MemFunCallbackStream

使用 List 类和 Pair 类的 C++ undefined reference 错误

c++ - 为什么将高数字传递给具有递归功能的函数会使我的控制台停止响应?

c++ - 使 C++ 成员函数根据模板参数更改不同成员变量的更优雅的方法?

C++模板函数错误: template-id does not match any template declaration