简体   繁体   English

为什么我的程序返回5?

[英]Why my program return 5?

I study templates and I must search max element < 0. But function return 5. 我研究模板,必须搜索max <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;
}

If you start this code, p at the end is 5 如果您启动此代码,则末尾的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;
}

And I don't know, what I must write here. 我不知道,我必须在这里写些什么。 What details need this site? 这个网站需要什么细节?

In the last time the loop 在最后一次循环

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

if executed you compare 如果执行,您比较

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

but arr_help[a] was never set and is possibly beyond the array bounds of arr_help . 但是arr_help[a]从未设置过,可能超出了arr_help的数组范围。 It may contain anything, thus setting p=a. 它可以包含任何内容,因此设置p = a。

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

相关问题 为什么我的程序在 return 语句处崩溃? - Why does my program crash at the return statement? 为什么我的程序在 if 语句中没有返回 0? - Why does my program not return 0 in an if statement? 为什么在访问指针的值时程序会返回垃圾? - Why does my program return garbage when accessing the value of a pointer? 为什么我的数独程序不返回输出? - Why doesn't my Sudoku program return an output? 如果我在程序的主 function 入口点结束时返回 EXIT_FAILURE,为什么什么也没有发生? - Why nothing happens if I return EXIT_FAILURE at the end of my main function entry point in my program? 尝试计算平均绝对偏差时,为什么程序返回inf? - Why does my program return inf when I try to calculate the Mean Absolute Deviation? 为什么glGetProgramiv GL_ACTIVE_UNIFORMS偶尔返回垃圾并使我的程序崩溃? - Why does glGetProgramiv GL_ACTIVE_UNIFORMS occasionally return garbage and crash my program? 为什么我的程序在O0和O2的优化级别上返回不同的结果 - Why my program return different results at optimization level of O0 and O2 为什么我的程序不打印字符串? - Why my program is not printing string? 为什么我的程序会打印垃圾? - Why is my program printing garbage?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM