0
The result of <avr> and <total> is <0> when the following code executes. Would anyone highlight the logical error please!
#include <iostream> using namespace std; main() { int eng, pashto, dari, total; total=eng+pashto+dari; float avr; avr=total/4; cout<<"Language Subjects"<<endl<<endl<<endl; cout<<"Enter Your English Marks:"; cin>>eng; cout<<"Enter Your Pashto Marks:"; cin>>pashto; cout<<"Enter Your Dari Marks:"; cin>>dari; cout<<"Your total marks are "<<total<<" and Percentage is "<<avr;
1 Resposta
0
When you are setting the total and avr variables, the subject variables are all uninitialized. So, when you tell the compiler you want total to be eng + pashto + dari, it's adding 3 random values together, but it seems the compiler is overriding it to be 0 since they are uninitialized. To fix this, move the total=eng+pashto+dari; and avr=total/4; lines to be just above the final cout.
Also, regarding the variable types, you shouldn't get in the habit or mixing types like that. It's poor programming. Because grades can have decimals (and even if they don't), you should set them to float. Lastly for your avr = total/4 line, you should be dividing by 3, not 4. There's only 3 subjects, so dividing by 4 won't give you the correct results. You should also write the 3 like this: 3.0f;
So, the code should like like this:
...
int main() {
float eng, pashto, dari, total, avr;
cout<<"Language Subjects"<<endl<<endl<<endl;
cout<<"Enter Your English Marks:";
cin>>eng;
cout<<"Enter Your Pashto Marks:";
cin>>pashto;
cout<<"Enter Your Dari Marks:";
cin>>dari;
total = eng + pashto + dari;
avr = total / 3.0f;
cout<<"Your total marks are "<<total<<" and Percentage is "<<avr;
...