gpt4 book ai didi

c - 在主函数中保持零

转载 作者:太空宇宙 更新时间:2023-11-04 02:51:30 24 4
gpt4 key购买 nike

我添加了一些 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com