【发布时间】:2017-11-29 06:56:47
【问题描述】:
我有一个项目在两个文件中,但我无法让主程序打印出平均变量,无论我改变什么,我都只会得到 0.0。它也没有打印出一个完整的其他功能任何提示?
Main File:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float average(void);
float std_dev(float);
float output(float);
float array[10] = {4.8, 12.98, 82.1, 5.98, 19.75, 24.9, 75.7, 3.45, 10.0, 28.11};
extern float avg;
int main()
{
float s = 0.0;
printf("The average value of the array is %.2f \n", avg);
s = std_dev(avg);
printf("The standard deviation of the array is %.2f \n", s);
return 0;
}
static void output(float var)
{
printf("The value of the variable is %.2f \n", var);
}
第二个文件:
#include <math.h>
extern float array[];
float avg = 26.78;
static float average()
{
int n;
float sum = 0.0, mean=0.0;
for(n=0; n<10; n++)
sum = sum + array[n];
mean= sum/10;
output(mean);
return mean;
}
float std_dev()
{
int n;
float cumm_diff = 0.0;
for(n=0; n<10; n++)
cumm_diff += (avg -array[n]) * (avg -array[n]);
return sqrt(cumm_diff/10);
}
【问题讨论】:
-
奇怪的是,你用
float代替double,却用sqrt()代替sqrtf()。 -
您应该尽可能避免使用无参数函数。如果您将数组作为长度加上指向开始的指针传递(例如
float std_dev(size_t num_data, float data[])。 -
程序编译后(有编译错误如
output()的声明和定义不同),avg变量打印就好了。 -
发布的代码包含大量
double文字。在所有情况下,它们都应该是float文字。要使它们成为float文字,请将f附加到每个文字的末尾。 -
关于:
static void output(float var)使用static修饰符背后的想法是该函数在当前文件之外不可见。建议将语句更改为:void output( float var )然后在第二个文件中插入语句:extern void output( float );
标签: c file debugging io syntax-error