The meaning is not getting the correct answer

int c;
int f = 20;
c = 5 / 9 * (f - 32);
Console.WriteLine(c);
Console.ReadLine();

      

If I run this code, c ends with 0, which is not correct. Can anyone tell me why?

+3


source to share


3 answers


Because your calculation is done on an integer type . I believe it c

is a double type variable.

c = 5d / 9 * (f - 32.0);

      



use 32.0

or 32d

to one of the operandsdouble

also does the same for 5/9

.

Also you need to define it c

as double.

+8


source


the problem lies in the following line:

5 / 9

      



since c and f are integers. For example, if I asked you to divide from 11 to 10; you tell me the result is 1.1. Suppose you don't know about floating point arithmetic, then you say either that it is impossible to divide from 11 to 10; or you say it is 1. The runtime environment does the same, it says it is 0 since you are declaring an integer.

+3


source


Khabib has already explained what is happening. Here's what you could do if you don't want to change c

to float or double:

c = (int)Math.Round(5.0 / 9.0 * (f - 32.0));

      

+1


source







All Articles