Hello, I am working on a project for my C++ class, I have nearly completed the project, and the code more or less works. However, I am getting hung up on one aspect. The project is small, its to write a program that calculates the equivalent resistance of "n" parallel resistors. The code I have written below works fine until "0" is inputed to calculate a new set.
Code:
# include <iostream.h>
int main(void) {
double Req, Resistor, firstResistor;
cout.setf(ios::showpoint | ios::fixed);
cout.precision(4);
do {
int n = 1;
do {
cout << endl;
cout << "Please input resistor-" <<n<< ", or 0 to quit: ";
if (n == 1) {
cin >> firstResistor;
if (firstResistor < 0 ) {
cout << "Error: Resistance must be positive";
cout << endl; //negative action//
continue;
}
if (firstResistor > 0) {
Req=firstResistor;
}
if (firstResistor == 0) { //exit statement
return 0;
}
}
else if (n > 1) {
cin >> Resistor;
if (Resistor < 0 ) {
cout << "Error: Resistance must be positive";
cout << endl;
continue; //negative action//
}
if (Resistor == 0) {
break;
} //exit statement
if (Resistor > 0) {
Req = ( 1. /(( 1./ Req )+( 1./ Resistor )));
}
}
n++;
} while ((firstResistor != 0) && (Resistor != 0));
cout << endl;
cout << "The equivalent resistance is : " <<Req<< " Ohms";
cout << endl;
}while ((firstResistor == 0) || (Resistor == 0));
return 0;
}
The output looks like the attached picture below.
I'm not sure why the program is showing the output after completing the first "if (n=1)" statement instead of looping again and going on to the "else if (n>1)." As you can see, it doesnt do it for the first set of resistances entered.
I have been toying with this for several hours, and still have not gotten a solution. I am a first time coder, and this is the first project I have coded completely from start to finish. Much of this might as well be greek to me, but I am trying to learn.
I am not asking for anyone to write this for me, I just need someone to shed some light on what I am doing wrong.
Thank you very much in advance.
EDIT: I think the problem is caused by the value of "resistor" still being zero from the first run, thus the program is only calculating the resistance of the first resistor "firstResistor" (which was changed to Req) Could this be the problem?