Feb 15, 2010 at 4:29pm UTC
Why doesn't this code calculate the correct average?
For example when the average should be 3 it displays 7
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#include <iostream>
using namespace std;
int main()
{
char Name1 [15];
char Name2 [15];
char Name3 [15];
int ID1;
int ID2;
int ID3;
float Mark1;
float Mark2;
float Mark3;
cout<<"Enter The First Students Information\n" ;
cout<<"Name: " ;
cin>>Name1;
cout<<"ID: " ;
cin>>ID1;
cout<<"Mark: " ;
cin>>Mark1;
cout<<"Enter The Second Students Information\n" ;
cout<<"Name: " ;
cin>>Name2;
cout<<"ID: " ;
cin>>ID2;
cout<<"Mark: " ;
cin>>Mark2;
cout<<"Enter The Third Students Information\n" ;
cout<<"Name: " ;
cin>>Name3;
cout<<"ID: " ;
cin>>ID3;
cout<<"Mark: " ;
cin>>Mark3;
cout<<Name1<<" " <<ID1<<" " <<Mark1<<"\n" ;
cout<<Name2<<" " <<ID2<<" " <<Mark2<<"\n" ;
cout<<Name3<<" " <<ID3<<" " <<Mark3<<"\n" ;
float Average=Mark1+Mark2+Mark3/3;
cout<<"The Average Mark is " <<Average;
cin.ignore();
cin.get();
}
Last edited on Feb 15, 2010 at 4:29pm UTC
Feb 15, 2010 at 4:32pm UTC
Think of your operator precedence. Division comes before addition so on line 38 you are dividing Mark3 by 3 and then adding Mark1 and Mark2 to that. Modify line 38 to:
float Average=(Mark1+Mark2+Mark3)/3
Feb 15, 2010 at 4:36pm UTC
Change it to float Average= (Mark1+Mark2+Mark3) / 3;
Other wise it would be calculating (Mark3 / 3) + Mark1 + Mark2.
Thats odd - I wrote that when there was no post there. Maybe the submit lagged lol.
Last edited on Feb 15, 2010 at 4:37pm UTC
Feb 15, 2010 at 4:40pm UTC
okay I forgot about the order of operations
edit: worked perfectly Thanks!
Last edited on Feb 15, 2010 at 4:41pm UTC