This is my first program. It calculates compounding interest with yearly contributions. Recently I've been trying to add more options to it such as a calculator that calculates affordability of buying a home. to be able to do this I put everything in an if statement activated by the input "interest" but this causes every line of code to repeat indefinitely.
main()
{
int Program;
cout << "enter desired program";
cin >> Program;
int interest = 5;
if (Program = 5)
{
char again = 'y';
double z, x, c, v, b, n, m, a, s;
while (again == 'y' || again == 'Y') {
cout << "enter starting amount : ";
cin >> z;
cout << "enter yearly contribution : ";
cin >> x;
cout << "enter number of years : ";
cin >> c;
cout << "enter average annual growth % : ";
cin >> v;
b = (v / 100);
for(double i = 1; i <= c; i ){
n = z * (pow((1 b), i));
m = n ((((pow((1 b), i)-1)) * x) / b);
a = z (x * (i));
s = ((z * (pow((1 b), (i-1) ))) ((((pow((1 b), (i-1) )-1)) * x) / b) x);
cout << "year " << i << ":" << (m) << "|| interest : " << (m - s) << "|| total interest : " << m - a <<endl;
}
// i is number of years growing
// ((((v / 100) 1)) * i ) = number of years * yearly growth
cout << "repeat program?";
cin >> again;
}//endwhileloop
}
}
this has been causing every line of code to run without any input and essentially breaking it. is an if statement the proper way to go about this or am I mistaken?
Once the program is completed I'd also like the option to go back to the beginning and choose a new one instead of repeating it with a while loop. I've heard "goto" is considered bad and unorganized but in this scenario would it be acceptable or is there a better way to go about this. Thank you for looking into this and I'd love any feedback to help me learn to code. :)
CodePudding user response:
Not shure what you want to do but check your if
if(Program = 5)
You did this to verify if Program is 5 but try
if(Program==5)
Maybe this will fix it. I suggest you to use a do while loop.
CodePudding user response:
I think the problem with your if statement causing an infinite loop is that it's missing an extra '=' sign i.e. if (Program == 5){...}
. For the second part of your question (wanting to go back to the beginning and choose a different program) you could have a menu initially with each program listed with an integer using a do-while loop and switch for each of the options. For example:
#include <iostream>
using namespace std;
void printMenu(void){
cout << "Menu: " << endl;
cout << "1. first" << endl;
cout << "2. second" << endl;
cout << "3. Exit" << endl;
}
int main() {
int option;
do {
printMenu();
cout << "Choose a program: " << endl;
cin >> option;
switch (option) {
case 1:
//code for first program
cout << "first" << endl;
break;
case 2:
cout << "second" << endl;
break;
case 3:
cout << "Exiting" << endl;
break;
}
cout << endl << endl;
}while (option != 3);
return 0;
}