简体   繁体   English

为什么在 C 中的 return 语句之后这个浮点数会发生变化?

[英]Why is this float changing after the return statement in C?

This is a very simple code, it's goal is to calculate the average of an array of grades (integers):这是一个非常简单的代码,它的目标是计算一系列成绩(整数)的平均值:

#include <stdio.h>

int calculateAverage(int grades[], int size){
    int sum = 0;
    for (int index = 0; index < size; index++) {
        sum += grades[index];
    }
    float average = (float)sum / size;
    printf("\nAverage: %f", average);
    return average;
}

void printAverage(int grades[], int size){

    printf("Grades: \n");
    
    for (int index = 0; index < size; index++) {
        printf("%d\n", grades[index]);
    }
    
    float average = calculateAverage(grades, size);
    
    printf("\nAverage: %f", average);

}

int main() {
    int grades[]  = {4, 6, 10, 2, 8, 9, 10, 7, 8, 5};
    size_t grades_size = sizeof(grades)/sizeof(grades[0]);
    printAverage(grades, grades_size);
}

When I print out the average in the calculateAverage function, the output is 6.9 (correct).当我在 calculateAverage function 中打印出平均值时,output 为 6.9(正确)。 However, after the average is returned to the printAverage function, the average is now 6.0, which makes no sense to me.但是,平均值返回到 printAverage function 后,现在的平均值是 6.0,这对我来说毫无意义。

Any help is appreciated, thanks:)任何帮助表示赞赏,谢谢:)

int calculateAverage(int grades[], int size)

this function return int value, change it to this:此 function 返回 int 值,将其更改为:

float calculateAverage(int grades[], int size)

then you can get float return然后你可以得到浮动回报

calculateAverage returns an int , so average got converted to an int , so that's why it returns 6 instead of 6.9 calculateAverage返回一个int ,因此average被转换为一个int ,这就是它返回6而不是6.9的原因

Change the return type to float .将返回类型更改为float

float calculateAverage(int grades[], int size)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM