-1
#include<stdio.h>

float avg(float x,float y,float z)

{
    
float avg=(x+y+z)/3;
    
 printf("average=%f",avg);

};

void main()

{
float phy,chem,bio;

 printf("enter physics marks");

 scanf("%f ",&phy);

printf("\n enter chemistry marks");

 scanf("%f ",&chem);


 printf("\n enter biology marks");

 scanf("%f ",&bio);

 avg(phy,chem,bio);

}

This program is find the average of three subject by the functions. But ,whenever I run this program it takes one extra value after giving input for physics variable.

What is the reason behind this problem and how do I solve this?

Geek
  • 1
  • 1

1 Answers1

1

Incorrect main definition:

The correct definition of the main function is either:

int main(void)

Or

int main(int argc, char *argv[])

The rest are either extensions or outdated, and do not conform to the standard.

OP's problem:

Average, which is the arithmetic mean, and is calculated by adding a group of numbers and then dividing by the count of those numbers.

Change:

float avg=(x+y+z)/2;

to

float avg = (x + y + z) / 3;

Unrelated:

Use double instead of float. The function scanf returns the number of elements it has successfully processed and assigned. Check for it.

Harith
  • 4,663
  • 1
  • 5
  • 20
  • I changed data type from float to double and change the definition of main as you given. But it doesn't work. – Geek Dec 12 '22 at 09:47
  • It works just fine on my system once I remove the extra whitespace in the calls to scanf. See https://stackoverflow.com/questions/19499060/what-is-the-effect-of-trailing-white-space-in-a-scanf-format-string – Harith Dec 12 '22 at 12:15
  • Thank you Haris . It works now – Geek Dec 12 '22 at 17:46
  • @Geek Anytime. Consider accepting the answer if you find it helpful. – Harith Dec 12 '22 at 17:47