0

[ C ]Having a problem in building program.

My code is as follow: #include<stdio.h> int main(void) { int a,b,c,d,e; float f; printf("Enter a:\n"); scanf("%d",&a); printf("Enter b:\n"); scanf("%d",&b); c=a+b; d=a-b; e=a*b; f=a/b; printf("c=%d\n,d=%d\n,e=%d\n,f=%d\n",c,d,e,f); return 0; } There is a trouble in division.I can't get the correct answer.I have tried a lot of way, including forced-type-transfer.However, I still cannot get a correct answer.Can anyone help me?

12th Oct 2019, 3:44 AM
Elder
5 Réponses
+ 4
Use float or double data types instead of int. You'll need to use %f or %lf format specifiers ●Dividing int by int will result in int only , fractional part is ommited. ●Even if you typecast result to float *after* division , you'll get float number but it'll have 0's after decimal point ex. (float)(3/2) will result in 1.0 not 1.5 ●You can follow this way (float)3/(float)2 ●Even if you have a variable of type float using it against %d format specifier will cause implicit typecasting to int https://codeforwin.org/2015/05/list-of-all-format-specifiers-in-c-programming.html
12th Oct 2019, 3:48 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 4
Elder notice these line scanf("%d",&a); scanf("%d",&b); You are taking input as integer(using %d) so even if you give float numbers they will be converted to integer. You can replace it with scanf("%f",&a); scanf("%f",&b);
12th Oct 2019, 4:16 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 3
Elder can't say anything without watching your code , what you have changed. Post it in playground and link it to your question https://www.sololearn.com/post/75089/?ref=app
12th Oct 2019, 4:48 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
0
update:I've tried such way to solve my problem,but still the app show some unexpected behavior.I wonder whether is the complier`s problem.
12th Oct 2019, 4:09 AM
Elder
0
have try,but the answer is still wrong.it seems like some sort of overflow.in fact,all calculation show error.
12th Oct 2019, 4:39 AM
Elder