从另一个函数返回后小数点后的数字消失了

Digits after the decimal point are gone after returning from another function

我是编程新手,最近在学校做作业。作业内容是计算一组数据的平均值。下面是我的代码。我发现正确的值是 93.974998,但终端显示的值只有 93.000000。

#include <stdlib.h>
#include <stdlib.h>
#include <stdio.h>
#include "stats.h"
int findmean(unsigned char *ptr, float count);

int main() {

  unsigned char test[SIZE] = {34, 201, 190, 154,   8, 194,   2,   6,
                              114, 88,   45,  76, 123,  87,  25,  23,
                              200, 122, 150, 90,   92,  87, 177, 244,
                              201,   6,  12,  60,   8,   2,   5,  67,
                                7,  87, 250, 230,  99,   3, 100,  90};

    float mean = 0;
    float length_data = SIZE;
    
    mean = findmean( &test[0] , length_data);
    printf(" mean of the data is %f \n", mean );

    return 0;
}

int findmean(unsigned char *ptr, float count){

    float total = 0;
    for(int i = 0; i < count; i++){
            
            total += *ptr;
            ptr++;
                    
    }
    printf("count is %f\n", count);
    
    return total/count;
}

如果我更改代码,而不是在 findmean 函数中除总值,而是在 printf 函数中除以 printf(" mean of the data is %f \n", mean/lenght_data );,那么答案将是正确的。

刚才没看懂,问题出在哪里?有人能告诉我哪里做错了吗?

顺便说一句,我使用的是geany,GCC版本是9.4.0,以防有人想知道。

Return 一个 浮点数 类型,而不是 int

// int findmean(unsigned char *ptr, float count);
...
// int findmean(unsigned char *ptr, float count){

float findmean(unsigned char *ptr, float count);
float findmean(unsigned char *ptr, float count){

float 对比 double

最好使用 double 作为 C 中的默认浮点类型。两者的精度都有限。使用 float 时会打印“正确值 ist 93.974998”,但数学上正确答案是 93.975。使用 double 除非有特定需要使用 float.

高级

下面是我对 mean 计算的编码方式。

// Use `double` return type.
// Array length in `size_t` - not too wide, not to narrow type for arrays sizing.
// Length first to allow for diagnostics on ptr[]
// Use `const`  to indiacte the refeneced data in `ptr[]` does not change.
double findmean_alt(size_t count, const unsigned char ptr[count]) {
  // Accumulate the integer sum of `unsigned chars in a wider integer
  unsigned long total = 0;
  for (size_t i = 0; i < count; i++) {
    total += ptr[i];  // Index into the data with `i`
  }

  printf("total is %lu\n", total);
  printf("count is %zu\n", count);

  // Perform the division with `double` math
  return 1.0 * total / count;
}

...并称它为

// mean = findmean( &test[0] , length_data);
// Declare `mean` and initialize in one step.
double mean = findmean_alt(sizeof test/ sizeof test[0], test);