开发者

Integer calculation not working as expected [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.
#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:

  1. Change the types of a through h from int to float or double (and change the corresponding conversion specifiers from %d to %f in the printf and scanf calls);

  2. 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 write p = ((float) g / 600) * 100.0;

As far as everything else:

  1. In a hosted implementation, main returns int, not void. Unless your compiler documentation specifically says that void main() is supported, use int main(void) or int main(int argc, char **argv) instead, otherwise you are invoking undefined behavior;

  2. 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. Use fgets() instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜