c - 函数不在 c 中返回结果(在项目文件中)

标签 c dev-c++

当我在 .c 文件中运行这段代码时,它可以工作,但是当我为它创建一个项目时,我调用的函数将只返回 0.00。为什么?为什么它在项目文件中不起作用?

我正在使用 DevC++。

#include<stdio.h>

float mean(int total, int max);

int main(){
    int i,max, total=0;
    int array[max];
    printf("Enter max: ");
    scanf("%d",&max);

    for(i=0; i<max; i++){
        scanf("%d",&array[i]);
        total+=array[i];
    }
    printf("Total: %d\n",total);
    printf("Mean: %.2f",mean(total,max));
    return 0;
}

float mean(int total, int max){
    float ave;
    ave=(float)total/max;

    return ave;
}

最佳答案

问题出在这两行代码上——你声明了 array 的大小成为max在你真正计算出什么值之前 max有这会导致无法解释的行为。您的代码曾经按预期工作很可能纯粹是偶然。

int array[max];
...
scanf("%d",&max);

做你想做的事情的方法是分配足够大的内存来容纳你的数组。您可能想要检查 max 是否也大于 0 以及 scanf找到了一个号码。但它的粗略要点是这样的:

int max;
int *array;
printf("Enter max: ");
scanf("%d",&max);
array=malloc(sizeof(int)*max);

/* your code goes here */

free(array);

关于c - 函数不在 c 中返回结果(在项目文件中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43094087/

相关文章:

c - Unix - 关于 & 和 ps

C++ 控制台 : Parsing METAR data

c++ - 读取bmp文件中的像素值

c - 如何使用 sscanf() 中的宏定义的可变宽度说明符

调用参数数量未定义的 C 函数

C 编程 - 将变量参数传递给 opendir

c - 这个C程序有什么问题?我总是出现一个我们没有输入的新数字?用Dev-C++编译

c - C 语言的基本插入排序算法(TDM-GCC 编译器)

c - 嵌套开关: why does the second switch command not accept an input?

c - 调用的参数太少