Why my code show error ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why my code show error ?

#include <stdio.h> int area(int x,int y); int main() { int x; int y; scanf("%d %d",&x,&y); int a= area(x,y); printf ("the area of rombus is :\n %d ",a); return 0; } int area(int x,int y){ x=1/2*x*y; return (x); }

12th Dec 2020, 1:05 PM
RD:programmer
RD:programmer - avatar
4 Answers
+ 3
In C, int/int always yields an int. fractional part is discarded. example. 1/2 evaluates to 0 not 0.5 because part after decimal point is discarded. if either operand of / is double another operand will be promoted to double type and expression will yield double value. example. 1.0 / 2 results in 0.5 For your code: use 0.5 (double) instead of 1/2 or use explicit type casting : (double) 1/ 2 * x * y; Also it'll be better if you declare x and y to be double instead of int. do not forget to change format specifiers accordingly for scanf and print statements. Change the return type of function area , otherwise return value will be casted to int causing loss of fractional part.
12th Dec 2020, 1:20 PM
๐Ÿ‡ฎ๐Ÿ‡ณOmkar๐Ÿ•‰
๐Ÿ‡ฎ๐Ÿ‡ณOmkar๐Ÿ•‰ - avatar
+ 1
#include <stdio.h> int area(int x,int y); int main() { int x; int y; scanf("%d %d",&x,&y); int a= area(x,y); printf("the area of rhombus is :\n %d ", a); return 0; } int area(int x,int y) { return ((1.0f/2) * (x*y)); }
12th Dec 2020, 1:16 PM
Flash
+ 1
Hey Mr. Unknown Your code is all right just take multiplication of 'x' and 'y' in brackets x=(x*y)/2; like this but as you declared x is an integer so area will only prints integer. I suggest to declare 'x' as float. HAPPY CODING ๐Ÿ˜€!
12th Dec 2020, 1:27 PM
Giriraj Yalpalwar
Giriraj Yalpalwar - avatar
0
No error - prints 0 as expected
12th Dec 2020, 1:12 PM
Volodymyr Chelnokov
Volodymyr Chelnokov - avatar