• 0

C++ Help


Question

The assignment:

Create a program that calls a function calcAverage that asks the user for 4 integers then displays the average of those numbers, which may require a decimal point.

My code:

/* comments can go here later */

#include <iostream>
using namespace std;
void calcAverage(float avg);

	int  num1	=	0.00;
	int  num2	=	0.00;
	int  num3	=	0.00;
	int  num4	=	0.00;
	float	avg  =	0.00;

void main()
{
	calcAverage(avg);
}

void calcAverage(float avg)
{
	cout << "Enter Number 1: ";
	cin >> num1;
	cout << "Enter Number 2: ";
	cin >> num2;
	cout << "Enter Number 3: ";
	cin >> num3;
	cout << "Enter Number 4: ";
	cin >> num4;

	avg = float((num1+num2+num3+num4)/4);

	cout << "Average of Four Numbers: " << avg << endl;
}

If I input 4, 4, 4, 5 it will give me the average is 4, which is incorrect. It should display 4.25. If I change num1 through num4 to float instead of int, it works, but that is not what the program asks.

I know I have to use a typecast somewhere in the calculation, but for some reason, it's not working?

Link to comment
Share on other sites

4 answers to this question

Recommended Posts

  • 0

avg=num1+num2+num3+num4;

avg=avg/4;

should work

[edit]

the reason y its working is that u r type casting it into floating pt after dividing by 4.

[\edit]

Edited by shake
Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.