c - 在主函数中保持零

标签 c function

我添加了一些 printf 语句来查看信息是否被计算机正确传递,并且在 calcMean 函数中被正确计算时,我在主函数中不断得到零。我不确定我的错误在哪里。

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

void calcMean(int [], int, float);
void calcVariance(int [], int, float);



int main(void)
{
/*create array and initialize it with values*/
int mainArr [ ] = {71,1899,272,1694,1697,296,722,12,2726,1899,
                ....... 
                    1652,488,1123,17,290,1324,2495,1221,2361,1244,
                    813,2716,1808,2328,2840,1059,2382,2391,2453,1672,
                    1469,778,2639,357,2691,1113,2131,23,2535,1514,
                    2317,45,1465,1799,2642,557,1846,1824,1144,1468,-1};
/*create initilized values for variables*/
float mean = 0.0;
int counter = 0;

calcMean(mainArr, counter, mean);

calcVariance(mainArr, counter, mean);

printf ("Mean: %10.2f\n", mean);       /*gives the average number to one decimal place*/
printf ("counter: %10.0d\n", counter);
getchar();
}/*End of the program*/

void calcMean(int mainArr[], int counter, float mean)/*This function finds the     Mean(average) of the function, and the size of the array*/
{   
int sentinel = -1;
float sum = 0.0;
int index = 0;
for (index; mainArr[index] != sentinel; index++) /*gets the total numbers in the function and the sum*/
{
    counter++;
    sum = sum + mainArr[index];
}       /*end of the sumation and counting of integers*/

printf ("%0.0d\n", counter);
mean = ((float) sum / counter);             /*Divides the sum by the total number of numbers to find the mean*/
printf ("mean: %10.2f\n", mean);
}

void calcVariance(int mainArr[], int counter, float mean)
{
int varindex = 0;
int numerator =0;
int square = 0;
int variance = 0;
int sumation = 0;
for(varindex; varindex<counter; varindex++)
{
    numerator = (mainArr[varindex] - mean);
    square = (numerator * numerator);
    sumation = sumation + square;
    variance = sumation / (counter-1);
}
printf ("variance %10.2f\n", variance);
}

最佳答案

您假设您的函数会更改外部变量的值。它不会。

calcMean(mainArr, counter, mean);
                  ^        ^ pass by value

void calcMean(int mainArr[], int counter, float mean)
                                 ^              ^ receive by value

在函数内修改counter只会改变局部变量。

关于c - 在主函数中保持零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21665851/

相关文章:

c - 作为变量和值传递的参数,都返回不同的答案

jquery - 如何在启动另一个循环函数时通过单击停止 jquery 循环函数

获取特定工作表名称的函数

c - 新手编译器问题

c - 使用 cblas 运行程序

c++ - 使用 scanf 进行输入过滤

c - 当您从 execvp 接收输出时,从管道中读取适量的数据

javascript - 为什么我只得到 2 和 3 为假? (如果数字是素数则返回真)

C 宏函数 If...Else 值

c - 解决这个识别功能?