Reputation: 67
I want to equate 24/5 in my console and display the equation and answer on screen (answer = 4.8), I have written my code as:
int answer = 24 / 5; //declare answer
Console.WriteLine("24 / 5 = " + answer);
Console.ReadLine();
I have tried using the variables decimal, double, float and int for answer but the console will always write the answer "4" and not "4.8".
Can anyone help please?
Upvotes: 0
Views: 1568
Reputation: 32511
When you write 24 / 5
, in this case the /
operator is the operator defined for the int type (because both sides are of int type) and so the result is an int
too. Try this:
double answer = 24 / 5.0;
Console.WriteLine("24 / 5 = " + answer);
When you provide one of the operands with a double type, in this case the double form of the /
operator will be used and the result will be a double too.
Upvotes: 1
Reputation: 223432
int answer = 24 / 5;
Everything above is int
, how do you expect to get a decimal point ? even if you change the type of answer
to double
this would not solve the problem since 24 / 5
still returns an integer value.
To get a double
value, atleast one of the operand should be of double
type. Like:
double answer = (double) 24 / 5;
Or
double answer = 24d / 5;
Or
double answer = 24.0 / 5;
Or
double answer = 24 * (1.0) / 5;
Or modify/cast 5
to double.
Upvotes: 2