Broken if else statement

The program is pretty simple. It takes 4 input values and compounds interest either over periods or continuously. The if statement won't work though. No matter what I do it always performs the else side of the statement.

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

int main ()
{
double s_amount = 0.0, interest = 0.0, term = 0.0, periods = 0.0, value = 0.0;

cout << "Enter deposit amount, interest, periods, and term: " << endl;
cin >> s_amount >> interest >> periods >> term;

if (periods == 0)
{
interest = interest/100;
value = pow(s_amount, exp(interest*term));
}
else if (periods != 0)
{
interest = interest/100;
value = s_amount*pow(1 + interest/periods,term*periods);
}

cout << "$" << fixed << showpoint << setprecision(2) << value << endl;

return 0;
}
Works fine for me...

I would recommend, since this is simple situation, do:
1
2
3
4
5
6
7
8
9
if (periods == 0)
{
    //...
}

else 
{
    //...
}
Last edited on
You should not compare for equality with floating point types (machine precision)
Make periods an integer or work with a tolerance
if( fabs(periods) < TOL )
Last edited on
For me, this program's if-else works fine. What makes you think if always performs the else side of the statement?

UPDATE: As a test, I put two different std::cout statements in both blocks, recompiled, and tested it with different numbers, making sure to change around the period value between 0 and some other value.. It worked just fine.

-Albatross
Last edited on
Well I changed everything to the specifications listed here but I'm still returning just the deposit amount whenever I put in 0 for the periods. Could my equation be faulty? I'm trying to compound continuously whenever 0 is input for periods. The equation is Deposit * e ^ x where e is euler's constant 2.17... and x is interest * term. Am I not using exp() correctly?
That's not the correct value of e.
e = 2.718281828459...
Yeah dyslexic typing, but what about the actual function for finding compound interest? I figured it would be pow(s_amount, exp(interest * term)) but I guess I'm wrong?
I haven't used these formulas in a while. I think the formula for compounding continuously is this:
$ = Principal*e^(rate*time)
Alright I went ahead and did this:


double s_amount = 0.0, interest = 0.0, term = 0.0, value = 0.0;
int periods;

cout << "Enter deposit amount, interest, periods, and term: " << endl;
cin >> s_amount >> interest >> periods >> term;

if (periods == 0)
{
interest = interest/100;
value = 1234;
}
else
{
interest = interest/100;
value = s_amount*pow(1 + interest/periods,term*periods);
}

cout << "$" << fixed << showpoint << setprecision(2) << value << endl;

With the value being some random number, when I input 0 for periods it should return 1234, but it still returns whatever deposit amount I enter by itself. What the heck???
Topic archived. No new replies allowed.