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); }
4 Antworten
+ 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.
+ 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));
}
+ 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 😀!
0
No error - prints 0 as expected