i am having a problem about doing percentage in my first c++ program please help me and tell me the error in my proram i am putting the code below there is in the percentage something wrong when i execute my program in MS DOS it shows the percentage=0 please kindly tell me the problem thanks.
#include <iostream.h>
main()
{
int totalmarks , obtain1 , obtain2 , obtain3 , gpa , cgpa , percentage , totobtain;
obtain1 = 0;
obtain2 = 0;
obtain3 = 0;
cout << "Please enter the marks of subject 1...=";
cin >> obtain1;
cout << "Please enter the marks of subject 2...=";
cin >> obtain2;
cout << "Please enter the marks of subject 3...=";
cin >> obtain3;
cout << " Please enter total marks";
cin >> totalmarks;
totobtain= obtain1+obtain2+obtain3;
percentage = totobtain/totalmarks*100;
cout << "=====YOUR RESULT==== Obtain marks in given 3 subjects are =" <<totobtain <<"....Percentage is =" << percentage;
first of all i dont no if ur getting an error but you need to use either std::cout or std::cin
another choice is below the header put using namspace std;
for the newline.
put std::endl or endl if u put namspace std;
here is your fixed code(i also changed header to a more modern version)
/*EDIT::::::::::::::::::::
i edited some stuff. i addend the endl's and
i put a loop so you can choose if you want to try again. when you do try again system("CLS")
will clear the screen of previous stuff.And you are missing return 0;*/
#include <iostream>
usingnamespace std;
main()
{
char loop='y';
do
{
system("CLS");
int totalmarks, gpa , cgpa , percentage , totobtain;
int obtain1 = 0;
int obtain2 = 0;
int obtain3 = 0;
cout << "Please enter the marks of subject 1...=";
cin >> obtain1;
cout << endl <<"Please enter the marks of subject 2...=";
cin >> obtain2;
cout << endl <<"Please enter the marks of subject 3...=";
cin >> obtain3;
cout << endl <<" Please enter total marks";
cin >> totalmarks;
totobtain = obtain1+obtain2+obtain3;
percentage = (totobtain/totalmarks)*100;
cout << endl << "=====YOUR RESULT==== Obtain marks in given 3 subjects are ="
<< totobtain <<"....Percentage is =" << percentage << endl;
cout << "Would you like to try again? [y/n]: ";
cin >> loop;
}
while(loop == 'y' || loop == 'Y');
return 0;
}
Quick explanation on why your code was not working (see Gey Wolf's post above for corrected version).
The line
percentage = (totobtain/totalmarks)*100;
was using integer arithmetic (as all varaibles were declared as int)
If we try toobtain = 120, totalmarks = 200
then toobtain/totalmarks = 120/200 = 0 !
0 * 100 = 0.
When you change these to Float, floating point arithmetic is used,
toobtain/totalmarks = 120.0/200.0 = 0.6
0.6 * 100.0 = 60.0.