Integer calculation not working as expected [closed]
#include <stdio.h>
#include <conio.H>
void main()
{
int a,b,c,d,e,f,g,i,h;
float p;
char A[10];
clrscr();
printf("Enter the name\n");
gets(A);
printf("Enter the ENG marks\n");
scanf("%d",&a);
printf("Enter the HIN marks\n");
scanf("%d",&b);
printf("Enter the MAR marks\n");
scanf("%d",&c);
printf("Enter the MAT marks\n");
scanf("%d",&d);
printf("Enter the SCI marks\n");
scanf("%d",&e);
printf("Enter the S.S marks\n");
scanf("%d",&f);
g=a+b+c+d+e+f;
p=(g*100)/600; //开发者_开发问答 <<-----
printf("NAME\t ENG\t HIN\t MAR\t MAT\t SCI\t S.S\t TOTAL\t PERCENTAGE\n");
printf("%s\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t %f\n",A,a,b,c,d,e,f,g,p);
getch();
}
The program works fine except for the line marked. What's the problem with it?
Convert to float before division
h=((float)g)/600;
This is truncating to an integer:
p=(g*100)/600;
Change that to
p=(g*100)/600.0;
Since h is declared as an int
, the line
h=(g/600);
will use integer division, not floating point division. Basically, this means that everything beyond the decimal point will be ignored. For example, giving the example 450/600
, floating point division would give you 0.75
, whereas integer division would give you 0
.
The subsequent line
p=(h*100);
takes this stored value of h, in this case 0
, and multiplies it by 100. Which is still 0
.
There are a lot of problems in this code.
The percentage isn't being computed correctly because you're using integer math for the division; for example, if g
is 500, the result of g/600
would be 0, which gets assigned to h
(also an integer).
There are several approaches:
Change the types of
a
throughh
fromint
tofloat
ordouble
(and change the corresponding conversion specifiers from%d
to%f
in theprintf
andscanf
calls);Cast
g
as a float before dividing by 600, or divide g by 600.0 (h
will still need to be typed as a float, or you can skip the that step and simply writep = ((float) g / 600) * 100.0;
As far as everything else:
In a hosted implementation,
main
returnsint
, notvoid
. Unless your compiler documentation specifically says thatvoid main()
is supported, useint main(void)
orint main(int argc, char **argv)
instead, otherwise you are invoking undefined behavior;NEVER NEVER NEVER NEVER NEVER NEVER use
gets()
; it will introduce a point of failure in your program. It was officially deprecated with C99, and is expected to be gone from the next version of the standard. Usefgets()
instead.
精彩评论