# Thread: Function not working properly. What am I missing?

1. ## Function not working properly. What am I missing?

I am currently a student in C, and I'm trying to learn functions. However, the very first demo code the book gave just does not work (I keep getting undefined results). I've triple checked and I have code down exactly, so I'm wondering if they forgot to include a header or if I'm missing something.

Code:
```#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double average (double a, double b)
{
return (a + b) / 2;
}

int main()
{
double x, y, z;
printf("Enter three numbers:");
scanf("%1g%1g%1g", &x, &y, &z);
printf("Average of %g and %g: %g\n", x, y, average(x, y));
printf("Average of %g and %g: %g\n", y, z, average(y, z));
printf("Average of %g and %g: %g\n", x, z, average(x, z));

return (0);
}```
This keeps outputting
Enter three numbers:234
Average of 1.8e-307 and 1.8e-307: 1.8e-307
Average of 1.79046e-307 and 7.96789e+268: 3.98394e+268
Average of 1.79064e-307 and 7.96789e+268: 3.98394e+268

Process returned 0 (0x0) execution time : 1.391 s
Press any key to continue.
Any ideas?

2. What will happen if you divide a double with an int ? You will get an int.This is what you do in the body of your function.This will cut off the decimal digits.In this case you have to return the return value of the function to int.

If you want to keep having double precision, divide by 2.0 not 2 and change the avg from int to double.

In case you have get confused with %g see here printf - C++ Reference

3. Actually, avg is the only thing that works (I actually thought I'd removed it, as it is not pertinent to the rest of the code. Sorry about that. It's removed now). I'm talking about how I'm inputting digits that are not being properly output. (i.e. in the first example, '2' is converted to '1.8e-307' and in the third example it's converted to '1.79064e-307' ).

4. 1. It says, "Enter three numbers." You're entering "234." That is one number. Separate them with spaces.
2. The format specifiers for the "scanf()" should be "%lg" - that one in the middle is a lowercase 'l' (ell). It appears you have the number 1 instead.

 Don't edit the code in your original post - it can make the following responses confusing as they are no longer applicable. Instead, reply with an updated version of your code.

5. Thank you, that was it. The font in my book (and my ide) make '1' and 'l' look exactly the same. What was happening was that '234' was getting counted as 3 numbers. It didn't make sense to me, but now it does.

Thanks again!

Also, I'll keep not editing in mind.

6. That is why, when we see it, we discourage people from using a lower-case ell as a single-letter variable name, as in many fonts it looks similar/identical to the number 1 and/or the capital letter 'I' (eye). I know that you did not do this here, but we do see it from time to time, and it's a good fact to be aware of.