-3

I wanted to ask you because when I run my program, I get that the arithmetic mean of 5 and 18 is 11, not 11.5? I put my program in C:

 #include <stdio.h>
 int main(void) {
     int a,b;
     a = 5;
     b = 18;
     printf("La media aritmética de %d i %d es %d\n", a, b, (a+b)/2);
     return 0;
 }

Thanks

5 Answers5

1

This is because you are using int instead of float or double. Integer division in C will provide only integer result by rounding off the output. Please use float instead of int or typecast the solution with float.

 float c;
 c = (float)(a+b)/2

However these are very basic C questions. Please go through C tutorial or C books for these kind of answers.

Avishek Bhattacharya
  • 6,534
  • 3
  • 34
  • 53
1

Modify your code like below -

#include <stdio.h>
 int main(void) {
     float a,b;
     a = 5;
     b = 18;
     printf("La media aritmética de %.f i %.f es %f\n", a, b,(a+b)/2);
     return 0;
 }

Currently, you are getting 11. Because when this operation (a+b)/2 is happening, it is saving the result in an integer. Which is ignoring the floating point value.

EDIT: If you want to print only 2 floating points then do the following -

printf("La media aritmética de %.f i %.f es %%0.2f\n", a, b,(a+b)/2);

For more info please see this Floating point rounding

Community
  • 1
  • 1
Naseef Chowdhury
  • 2,357
  • 3
  • 28
  • 52
1

Change the data type of a and b to float/double.

Owen Xu
  • 11
  • 1
  • 2
0

#include

int main(void)

{

 float a,b,c;

 a = 5.0;

 b = 18.0;

 c=(a+b)/2;

 printf("La media aritmética de %f i %f es %f\n", a, b,c  );

 return 0;

}

0

Problem in your code is data type.When dividing any numbers, sometimes it return whole or decimal value.

For eg,

Let divide 10/2=5 and 10/4=2.5. Thus,be aware in allocate datatypes.

For your problem,there are lot of ways to solve,

1.Change data type of particular answer storing variable

2.Change data type for all process involving variables

3.Change format specifier

4.Typecasting