I wrote some code for an assignment i have in c. The code does not have any syntax error but the result it prints is wrong and i can’t figure out why. I tried assigning the value i wanted to the result variable and print it and it worked fine. Here is the code:
#include <stdio.h>
int main(){
long kwdikos;
double ethsios_misthos, evdomadiaia_amoivh, amoivh_ana_ora;
int ores_ergasias;
printf("Dwse ton kwdiko: ");
scanf("%ld", &kwdikos);
if (kwdikos >= 1000){
printf("Dwse ton ethsio mistho: ");
scanf("%g", ðsios_misthos);
evdomadiaia_amoivh = ethsios_misthos / 52;
printf("H evdomadiaia amoivh einai: %g", evdomadiaia_amoivh);
}
else{
printf("Dwse tis ores evdomadiaias ergasias: ");
scanf("%d", &ores_ergasias);
printf("Dwse thn amoivh ana ora: ");
scanf("%g",&amoivh_ana_ora);
if (ores_ergasias > 40){
evdomadiaia_amoivh = 40 * amoivh_ana_ora + (ores_ergasias - 40) * 1.5 * amoivh_ana_ora;
}
else{
evdomadiaia_amoivh = ores_ergasias * amoivh_ana_ora;
}
printf("H evdomadiaia amoivh einai: %g", evdomadiaia_amoivh);
}
return 0;
}
I expected evdomadiaia_amoivh to be a number but when i run this code and print it the result is 1.09e something and i dont know why.
printf("%g", some_floating_point_value);
prints in fixed point format akin to "%f"
when the magnitude of the value is neither larger nor small. It prints in exponential format, akin to "%e"
, other wise. Example: 1.09e08
Use "%f"
or "%F"
to always print in a fixed point manner.
Well, perhaps you can run it and show us what’s printed out, and tell us from where is the code behaving not as expected? That’s much more helpful than throwing a chunk of code and wishing it to be rectified; that’s what you do with a paid service.
The possible formats to display a floating number are
%f
,%e
or%g
. If you do not want the value printed with an exponent (like1.09e+2
), you must use%f
not%g
.You need to learn to use a debugger, and also add some intermediate printouts of the results so that you can see where it goes wrong.
test the result of scanf too
Thanks it was indeed that i used g instead of lf and f.