pfc
pfc

Reputation: 1910

c language printf float error

I define a function finding the mean value of an array of int, the function is as follows:

float MeanInt(int x[],int num){
    float mean, sum = 0.0f,res=0.0f;
    int i;
    for(i=0;i<num;i++){
        sum += (float)(x[i]);
        printf("x[%d] is %d\n", i,x[i]);
        printf("sum is %f\n", sum);
    }
    res = sum/((float)(num));
    printf("mean should be %f\n", res);
    return res;
}

the printf() within this function all works correctly. The problem is that when I use it in my project, like follows:

printf("mean number is %f\n", MeanInt(ls_tr_acl,num_round));

I meet with an error saying that: format %f expects argument of type double, but argument 2 has type int I'm fully confused because the printf() within the function MeanInt() print out exactly the correct result. I also test MeanInt() on some toy examples and it always works correctly. The problem only happens when I run it in my project.

Upvotes: 0

Views: 194

Answers (1)

Mohit Jain
Mohit Jain

Reputation: 30489

You are not declaring the function MeanInt before its first invocation so compiler assumes the type of MeanInt is a function returning int taking any number of arguments.

Fix
Include appropriate header file (containing the declaration), or move the definition above usage or declare it before usage as:

float MeanInt(int x[],int num);

You can declare it at global scope at the top of the file or in narrower scope also.

Upvotes: 2

Related Questions