Reputation: 15
I have this program that makes a geometric mean, I know it can be done with cbrt instead of pow, but my question is the next
//medida geometrica de 3 numeros
#include<stdio.h>
#include<math.h>
int main(){
double n1, n2, n3, mult, media;
printf("introduce los 3 numeros espaciados con un espacio cada uno:");
scanf("%lf %lf %lf", &n1, &n2, &n3);
mult = n1 * n2 * n3;
media = pow(mult, 1/3.);
printf("\nLa media geometrica es de:%lf", media);
}
The question is why pow gives me a wrong value if I don't write a dot after the 3 in the pow function pow(mult, 1/3.)
I mean if i write pow(mult, 1/3) without the dot after the 3 it gives me a wrong value and I don't know why
Thanks in advance.
Upvotes: 1
Views: 57
Reputation: 8871
There is a big difference in the result of 1/3
and 1/3.
.
The first uses integer division. The quotient is 0
and the remainder is 1
, which is thrown out (or truncated), resulting in final value of 0
.
The second uses floating point division which results in the expected value, (approximately) 0.333...
.
Upvotes: 2
Reputation: 225827
When you do 1/3
, both arguments have integer type so the result is also an integer and you get 0.
When you do 1/3.
, one argument has type double
so the other is converted to that type and floating point division is done, so you end up with the expected value.
Upvotes: 2