0
#include<stdio.h>
int main(){
    int a, b, c;
    printf("Enter any three numbers:");
    scanf("%d %d %d", &a, &b, &c);
    float avg = (a + b + c)/ 3;
    printf("%.2f", avg);
    return 0;
    } 

I could obtain only the integer part of the output with 0 in the decimal part

  • 2
    the result of (int)/(int) is (int) – Cid Sep 02 '22 at 12:58
  • You just need to have a float in your computing. Otherwise the result (from (int)/(int)) will be an int. For example just divising with `3.0f`should resolve your issue. – yaourtiere Sep 02 '22 at 13:56

2 Answers2

3

You're dividing by 3, which is an integer. You should cast one of the two operands to float, or divide by 3.0f. Examples:

(float) (a + b + c) / 3; // cast operator has the precedence over division operator
(a + b + c) / (float) 3;
(a + b + c) / 3.0f;

From the Current C Programming Language StandardISO/IEC 9899:2018 (C18), you can read that When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded:

6.5.5 Multiplicative operators
Syntax
1 multiplicative-expression:
cast-expression
multiplicative-expression * cast-expression
multiplicative-expression / cast-expression
multiplicative-expression % cast-expression

Constraints
2 Each of the operands shall have arithmetic type. The operands of the % operator shall have integer type.

Semantics
3 The usual arithmetic conversions are performed on the operands.
4 The result of the binary * operator is the product of the operands.
5 The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.
6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.109) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a; otherwise, the behavior of both a/b and a%b is undefined.

mikyll98
  • 1,195
  • 3
  • 8
  • 29
0

Integer arithmetic yields an integer result - 1/2 == 0, 3/2 == 1, 5/2 == 2, etc. Even though you're assigning the result to a float, there's no fractional portion to save.

To get the result you want, you'll want to change

float avg = (a + b + c)/ 3;

to

float avg = (a + b + c)/ 3.0f;
John Bode
  • 119,563
  • 19
  • 122
  • 198