Click here to Skip to main content
15,885,871 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why is my function not working? why I am getting marks percentage 0?
Enter marks received in 3 subjects: 45 65 76 
0


What I have tried:

C
//function for the percentage of marks
int marks_percentage (int a, int b, int c)
{
    int sum, percentage, total_marks;
    sum = a+b+c;
    total_marks = 300;
    percentage = sum/total_marks*100;
}

int main()
{
    int a, b, c, mp;
    printf ("Enter marks received in 3 subjects: ");
    scanf ("%d %d %d", &a, &b, &c);
    
    mp = marks_percentage (a,b,c);
    printf ("%d" , mp);
}
Posted
Updated 28-Mar-21 7:30am
v3

It is because you are working with integers.

Because the sum (186) is being divided by 300 you end up with 0.62 which cannot be represented as an integer and therefore the answer is 0.

Try the following

percentage = sum * 100/total_marks;
 
Share this answer
 
Comments
Tony Hill 28-Mar-21 7:52am    
Well spotted Patrice T, I knew the maths was wrong but did not spot the lack of a return.
Patrice T 28-Mar-21 8:07am    
My 5, good catch too.
Quote:
Why my function not working?

try to return a value from the function:
C++
int marks_percentage (int a, int b, int c)
{
    int sum, percentage, total_marks;
    sum = a+b+c;
    total_marks = 300;
    percentage = sum/total_marks*100;
    return ...
}
 
Share this answer
 
Apart from the issue that Tony Hill notes above, you are not returning the percentage value to the caller. So you need the following:
C++
int marks_percentage (int a, int b, int c)
{
    int sum, percentage, total_marks;
    sum = a + b + c;
    total_marks = 300;
    percentage = sum * 100 / total_marks;

    return percentage; // you need to return the calculated value.
}
 
Share this answer
 
Comments
KarstenK 28-Mar-21 13:32pm    
I prefer using braces when dividing integers to make the compiler really clear what the result should be.
percentage = (sum * 100) / total_marks;
Richard MacCutchan 28-Mar-21 14:04pm    
Me too if it is possible to mis-interpret the intent. But in a simple sum like this I do not think it is necessary.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900