C# Question: Create a function that takes three integers from the input. The app
ID: 3753882 • Letter: C
Question
C# Question:
Create a function that takes three integers from the input. The app will return the rounded average of these integers using only integer operations (e.g. integer division with / and modulus (the remainder operator) with %) to accomplish this, so do not use float, double, or decimal data types, functions, and operations.
If your numbers are 1, 2, 4, the rounded average is 7/3 or 2. However, if your numbers are 1, 2, 5, the rounded average is 8/3 or 3. Likewise, if your numbers are -1, -2, -4, the rounded average is -7/3 or -2; and if your numbers are -1, -2, -5, the rounded average is -8/3 or -3.
Explanation / Answer
Given below is the code for the question.
Please do rate the answer if it was helpful. Thank you
using System;
public class Test
{
public static int Avg(int num1, int num2, int num3)
{
int total;
int avg, rem;
total = num1 + num2 + num3;
avg = total / 3;
rem = total % 3;
//adjust the avg by rounding
if(rem >= 2)
avg++;
else if(rem <= -2)
avg--;
return avg;
}
public static void Main()
{
Console.Write(" Calculate the rounded average of three numbers using / and %: ");
Console.Write("-------------------------------------------------- ");
Console.Write("Enter firt number: ");
int n1= Convert.ToInt32(Console.ReadLine());
Console.Write("Enter second number: ");
int n2= Convert.ToInt32(Console.ReadLine());
Console.Write("Enter third number: ");
int n3= Convert.ToInt32(Console.ReadLine());
Console.WriteLine(" The rounded average is : {0} ", Avg(n1,n2, n3) );
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.