-6
#include <stdio.h>

//Compiler version gcc 6.3.0

int main() {

    float da,hra,s,gs;

    scanf("%f",&s);

    da=40/100*s; hra=20/100*s;

    gs=s+da+hra;

    printf("%f",gs);

    return 0; 
}

For example if i entered 25000 for s then output must be 40000 but it showing 25000.000000.

user94559
  • 59,196
  • 6
  • 103
  • 103
  • Considering this isn't valid C code from the very first line? – StoryTeller - Unslander Monica Sep 17 '17 at 07:09
  • If you indent the code by 4 spaces, you can write `#include ` on the first line. Or you need to explain what you mean by 'the editor'. Note that you should write `#include ` — there really isn't an excuse to write `#include "stdio.h"`. – Jonathan Leffler Sep 17 '17 at 07:24
  • Next time, printf out those intermediate results like 'da', 'hra', (or use a 'real' debugger). Had your done so, you would probably have avoided an SO question and got your ap working quicker:( – Martin James Sep 17 '17 at 08:33

2 Answers2

1

Try the fix below.

Note the 40.0 and 20.0 instead of 40 and 20. The issue is that you were doing integer division. 40 / 100 == 0, so da was always 0. Using 40.0 / 100 instead gives you floating point division and the value 0.4, which is what you want to make your calculations correct. (The same holds for the computation of hra.)

#include <stdio.h>

int main() {
    float da, hra, s, gs;

    scanf("%f", &s);

    da = 40.0 / 100 * s;
    hra = 20.0 / 100 * s;
    gs = s + da + hra;

    printf("%f", gs);

    return 0;
}
user94559
  • 59,196
  • 6
  • 103
  • 103
0

In c, when several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence(priority) but multiplication and division have same precedence hence if two operators of same precedence is present in an expression, associativity of operators indicate the order in which they execute. Here the associativity is from left to right. (You can read more about it here What is associativity of operators and why is it important?).

So when evaluated from left to right 40/100 undergoes integer division to give 0 and when multipled with s the result of da was also 0 and and same with hra giving the result 25000. All you had to do was write

da = s*40/100 and hra = s*20/100.

The the entire value would have been treated as float and your result would have been correct. As implemented below,

#include<stdio.h>

//Compiler version gcc 6.3.0

int main() {

float da, hra, s, gs;

scanf("%f",&s);

da = s*40/100; 
hra = s*20/100;

gs=s+da+hra;
printf("s=%f, da=%f, hra=%f\n",s,da,hra);

printf("%f",gs);

return 0; 
}
ranger_sim_g
  • 160
  • 1
  • 10