i have to build a program to cacluate the weighted percent.

when ever the code is compiled it is giving the output to be 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  #include<iostream>
using namespace std;
int main()
{
    //intillization of the marks and weightage of the marks,.
    int mark1,mark2,mark3,mark4;
    double weight1,weight2,weight3,weight4,weightedaverage;
    cout<<"Please enter all the four marks obtained in the test."<<endl;
    cin>>mark1>>mark2>>mark3>>mark4;
    cout<<"please enter the respective weightage of the marks."<<endl;
    cin>>weight1>>weight2>>weight3>>weight4;
   weightedaverage=mark1/100*weight1+mark2/100*weight2+mark3/100*weight3+mark4/100*weight4;
    cout<<"The weightedaverage is" <<weightedaverage;
    return 0;


}
You have a problem with integer division.

If you divide two integers then the result has to be an integer, and this is formed by truncation toward 0. Thus for example,
265 / 100 gives 2
and, in this case,
70 / 100 gives 0

It is sufficient to make one of the operands a double. This will convert the other operand to a double also before doing the division and produce the expected answer (to within floating point accuracy).
70 / 100.0 gives 0.7

There are many ways of achieving that here. Some possibilities are:
- replace 100 by 100.0 (add the decimal point) in all occurrences on line 12;
OR
- multiply by the weights FIRST in each part, which ensures that intermediate results are also double (e.g. weight1*mark1/100 etc.)
OR
- replace 100 by a double variable, say: double total = 100.0;
OR
- make mark1, mark2 etc. double rather than int
OR
- explicitly cast one or other of the integers to a double before doing the division.
Last edited on
Topic archived. No new replies allowed.