I am new to C++ and currently trying to learn WHILE loop. But there is a problem I don't understand about my code that gave me a result different from what I expected. Here is it:
int i = 1;
double ans = 1.00;
while (ans > 0.1) {
ans = 1 / i;
i++;
}
cout << "ans: " << ans;
I am expecting to have: ans : 0.1, but is was always giving me: ans : 0. Can you tell me what I have done wrong. Thanks for your help.
The decision on whether to do integer or floating point division depends on the type of the operands.
Unless at least one of them is of floating point type, you will have an integer division.
The type of the variable you assign the result to does not matter.