0

This is my code, please help me out, percentage showing 0.00 instead of what i want.

I want to calculate percentage, as you will know this by code below...

#include<stdio.h>
#include<conio.h>

int main()
{
int marks[2][3]={80,70,50,90,50,60};
int total[2]={0,0};
float per[2]={0.0f,0.0f};

for (int x=0;x<2;x++)
{
for(int y=0;y<3;y++)
{
printf("[%d][%d]=%d\t",x,y,marks[x][y]);
total[x]=total[x]+marks[x][y];
per[x]=total[x]/300*100;
}

printf("total [%d]=%d",x,total[x]);
printf("\n\npercentage [%d]=%2.2f \n",x,per[x]);
putchar('\n');
}

getch();
return 0;

}
Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208
  • As suggested by others, use `total[x]/300.0f*100.0f`, also note that `marks` is declared as a 2D array but initialized as a 1D array, this is UB. – David Ranieri Sep 29 '14 at 11:30

2 Answers2

5

In the expression

total[x]/300*100

all involved values are integers, so the result is truncated before the assignment to the floating point array entry.

Change to e.g.

total[x]/300.0f*100.0f
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks a lot buddy, you solved it, but more than solving it, you taught me logic that why it was not correct, Thank you again. – Dayyan JD Sep 29 '14 at 11:31
2

Replace per[x]=total[x]/300*100; with per[x]=total[x] * 1.0f / 300 * 100;

You need to convert int to double / float before division to make sure you don't loose the precision because of truncation of integer division.

per[x]=total[x]/300*100;  /* Assuming total[x] = 280 */
per[x]=280/300*100;
per[x]=(280/300)*100;  /* Associativity is left-to-right */
per[x]=0*100;
per[x]=0;

You may also want to read integer division in C and operator associativity

Community
  • 1
  • 1
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100