Reputation: 1451
int c;
int f = 20;
c = 5 / 9 * (f - 32);
Console.WriteLine(c);
Console.ReadLine();
If I run this code c ends up being 0, which is wrong. Can anyone tell me why?
Upvotes: 3
Views: 157
Reputation: 12195
Habib already explained what is happening. Here is what you could do if you don't want to change c
to a float or double:
c = (int)Math.Round(5.0 / 9.0 * (f - 32.0));
Upvotes: 1
Reputation: 14919
the problem is in the following line;
5 / 9
because c and f are integers. For instance, if I asked you to divide 11 to 10; you will tell me the result is 1.1. Assume that you do not know about floating point arithmetic, then you will say either it is not possible to divide 11 to 10; or you will say it is 1. Runtime environment does the same, it says it is 0 since you are declaring an integer.
Upvotes: 3
Reputation: 223187
Because your calculation is being done in integer type. I believe c
is double type variable.
c = 5d / 9 * (f - 32.0);
use 32.0
or 32d
so that one of the operands is double
, also do the same for 5/9
.
Also you need to define c
as double.
Upvotes: 8