This code defines a function avg_calc
that calculates the average of two integer numbers and returns the result as a float value. The main
function uses this function to calculate the average of two numbers inputted by the user.
#include <stdio.h>
float avg_calc(int x, int y)
{
float result = (x + y) / 2;
return result;
}
int main()
{
int number1, number2;
float average;
printf("Simple Average Calculator: \n");
printf("Enter First Number: \n");
scanf("%d", &number1);
printf("Enter Second Number: \n");
scanf("%d", &number2);
average = avg_calc(number1, number2);
printf("Average of %d and %d is: %10.2f \n", number1, number2, average);
return 0;
}
Result:
Simple Average Calculator:
Enter First Number:
10
Enter Second Number:
6
Average of 10 and 6 is: 8.00
Process returned 0 (0x0) execution time : 5.091 s
Press any key to continue.
The program starts by including the stdio.h
header file which provides input/output functions like printf
and scanf
.
The avg_calc
function takes two integer parameters, x
and y
. It calculates their average by adding them and dividing the result by 2. The average is stored in a float variable result
and returned.
The main
function starts by declaring three variables: number1
, number2
, and average
. It then prints a prompt asking the user to enter the first number using printf
and reads the user's input using scanf
.
Similarly, it prompts the user to enter the second number and reads their input using scanf
.
Next, it calls the avg_calc
function with the two numbers inputted by the user, and stores the returned value in the average
variable.
Finally, the main
function prints the result using printf
with a formatted string that displays the inputted numbers and the calculated average with two decimal places.
The program ends by returning 0 from the main
function.
No comments:
Post a Comment