Fraction folly - rounding down to uselessness.
Hello, everyone. First time poster here. I'm rather inexperienced with C++, and I was wondering if anyone could help me out.
The problem is that I have declared a float, which I have called pi, but when I make an attempt to add, say, (1 / 5) to pi, the addition is rounded to the nearest whole number. (In this case, zero.)
So, is there any way of doing this? It is necessary that I add the number in numerator/denominator style, so decimal is out of the question.
A couple of topics to look up.
Hmmm... In most cases, when you combine different types in a single statement, C++ will promote the types automatically, and you shouldn't get this problem.
Look-up typecasting (aka casting) and type-promotion.
Typecasting makes one type of variable "behave like' another type. The simplest way to typecast is to put the desired type in parenthesis in front of the variable:
Now, typecasting should be used rarely. Generally, you should design your programs to use the "correct" variable types. IMHO, about the only time you should use typecasting is because you , you need to pass the "wrong" type into a library function that you didn't write.
int x = 1;
y= (float)x; // Cast x to a float. (not really required here)