Reputation: 166
int x;
scanf("%d",&x);
x=(double)((x*3.14)/180);
printf("%.6lf",x);
When I run the above code and input x=60, I get -0.000000.
int x;
double a;
scanf("%d",&x);
a=(x*3.14)/180;
printf("%.6lf",a);
But when I run this above code, I get the correct answer.
I want to know where I am doing wrong. Is there problem in my type casting or use of double or any other thing? Any help will be appreciated. Thanks!
N.B. : I need to print output upto 6 digits after decimal.
Upvotes: 0
Views: 84
Reputation: 50775
There are two problems in your code:
x = (double)((x*3.14)/180);
(x*3.14)/180
is already a double
therefore this line is equivalent to:
x = (x*3.14)/180;
but anyway the type of x
remains int
, so if x
was e.g 300
, the new values of x
will be 300 * 3.14/180 = 5.2333
which will be trunacated to 5
.
The second problem is here:
printf("%.6lf",x);
As explained before, the type of x
is int
, but the "%.6lf"
format specifier requires a double
. If the variable types don't match the format specifier, the behaviour is undefined.
The second version of your code is perfectly correct, but be aware that the user can only enter integer values.
BTW: 3.14 is a very poor approximation of PI, I'm sure you can do better.
Upvotes: 5