So, i was planning to give a little introduction on programming in C to my gf, and this problem showed up while i was writing one of the programs for it. Here is the program:
#include<stdio.h>
float sum(x,y) {
float u = x+y;
return u;
}
int main(void) {
float x = 30.134;
float y = 392.133;
float z = sum(x,y);
printf("%f \n",z);
}
The problem is, whe i run this program, it returns 422.000000, instead of the correct result 422.267000. I don't get it: If i'm not using any "int" here, why is the program truncating the result? I've always tought that the program will truncate numbers if they are floats or doubles declared as integers. But i don't see clearly why the program is truncating the numbers here. Thanks.
The default type in old C is int
. You need to declare your parameters properly if you want them to be typed your way:
float sum(float x, float y)
// ^^^^^ ^^^^^