![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Hobbyist Programmer
Join Date: Mar 2005
Posts: 148
Rep Power: 4
![]() |
I'm getting the wrong answer
This program I've got uses an array and calls a function to find the average of the integers in the array. The integers in the array are 9, 4, 6, 8, 10 and when you add them up you get 37. When you divide by 5 you get 7.4.
I do not want to lose the fractional part of the answer so that's why I'm using the static_cast< >operator. I also always want the answer to be output with a fixed decimal point and two digits of precision to the right of the decimal point. But my output says "The average is 7.00" instead of "7.40" like it should. I'm not sure where I'm going wrong. Here is the code: int findAverage(int j[]);
int main()
{
int numbers[] = {9, 4, 6, 8, 10};
double average = 0.0;
cout << "The values in the array are: ";
for (int i = 0; i < 5; i++)
cout << numbers[i] << " ";
cout << endl;
average = findAverage(numbers);
cout << "The average of the values is: " << setprecision(2)
<< setiosflags(ios::fixed | ios::showpoint)
<< average;
cout << endl;
return 0;
}
int findAverage(int j[])
{
int total = 0;
for (int i = 0; i < 5; i++)
total += j[i];
return static_cast<double>(total) / 5;
}Last edited by 357mag; Jun 8th, 2007 at 3:25 AM. Reason: Mistake |
|
|
|
|
|
#2 |
|
Programming Guru
![]() Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,261
Rep Power: 5
![]() |
A function that returns int can never return a value that is not an integer. Try making findAverage() return double, and return from it using;
return total/5.0; |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Code compiled without error, but gets the wrong answer; Calculating Volume | Fall Back Son | C | 15 | Oct 21st, 2006 7:51 PM |
| Wrong answer | Edgar | Assembly | 6 | Jul 12th, 2006 8:17 PM |
| [Python] Simple Comment Stripper | UnKnown X | Show Off Your Open Source Projects | 0 | Feb 10th, 2006 8:57 AM |
| First Python Programme: Fibonacci Finder | UnKnown X | Python | 2 | Dec 15th, 2005 7:19 PM |
| What is wrong with this code? | c0ldshadow | Visual Basic .NET | 5 | Dec 5th, 2005 6:37 PM |