I need help! The boolean in my while loop isn't working!

Okay, so, I am doing a while loop. Here is the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std; 
int main() {
	float principal, interest, interest2, payment;
	
	principal = 10000;
	
	interest = 99; 
	
	interest = interest / 100; 
	interest = interest / 12; 
	
	interest2 = principal * interest;  
	
	
	// Interest2 is equal to 825 when you do the math. 
	
	while (payment < interest2)
	{
	cout << "Enter payment." << endl; 
	cin >> payment; 
}
return 0;}


I put in 825 and the loop keeps running even though it shouldn't. 825 is not less than 825. Anyone know why this isn't working?

closed account (N8RzwA7f)
try != instead of <
This is due to the limited precision of floats. Prefer to use double over float, for increased precision. I've modified your code to demonstrate this.
1
2
3
4
float principal, interest, interest2, payment = 825;
// ...
if (payment == interest2) std::cout << "equal\n";
else std::cout << "not equal\n";

not equal


1
2
3
4
double principal, interest, interest2, payment = 825;
// ...
if (payment == interest2) std::cout << "equal\n";
else std::cout << "not equal\n";

equal
Last edited on
Even with doubles, equality comparison against floating-point numbers is prone to errors when both of the results are computed.

It looks like you're doing math with money. You won't be surprised to hear that binary floating-point numbers are not used in financial environments.
See, e.g., t http://www.netlib.org/misc/intel/

For your purposes, you can use integers instead. Put your currency into an integer, with plenty of extra precision. e.g., $12.34 can be represented as an integer like 12,340,000. It's possible to round integers nicely.

You shouldn't compare floating-point numbers for equality unless you have a good reason.

Binary floating point mathematics is relatively arcane. If you are unfamiliar with the formats, you may generate results that are very unexpected, or solutions which appear to work but break down around the limits of the representations.

With this in mind, there are plenty of solutions sitting around the net for e.g., floating-point equality that are subtly wrong. Watch out for them.
Last edited on
Well, everyone, I found a way around this issue. In the loop, I can add 1 to make the variable 826. The boolean in the loop fails and it continues with the rest of the program. Outside the loop, I can subtract 1 and make it 825, just how I originally wanted it. Therefore, I can use decimals and floats.
Topic archived. No new replies allowed.