I can only answer the question indirectly, because I didn’t start looking into the actual problem until after I had cleaned the code up a little bit – but now I don’t get the error. So, the answer is: clean up the code and it’ll probably work as expected.
I’ve kept saving the result in different variables although nothing in the program needs to have more than one result
variable as it is right now. The main flow of the program should be like your original but it’s just a tad easier to read now:
#include <iostream>
#include <string>
// helper functions
bool yes_or_no(const std::string& question) {
char answer;
do {
std::cout << question << " (y/n) ";
std::cin >> answer;
} while(answer != 'y' && answer != 'n');
return answer == 'y';
}
void line() { std::cout << "-------------------------------------\n"; }
void display_result(const std::string& heading, float value) {
std::cout << heading << " ta dva broja je: " << value << "\n";
}
int main() {
float op_a, op_b, add_res = 0, mul_res = 0, sub_res = 0, div_res = 0;
char oper;
bool save_op_a = false;
system("color B");
while(true) {
system("cls");
if(save_op_a == false) {
std::cout << "Unesite broj a: ";
std::cin >> op_a;
} else
save_op_a = false;
std::cout << "Unesite broj b: ";
std::cin >> op_b;
while(true) {
std::cout << "Unesite funkciju (+,-,*,/): ";
std::cin >> oper;
line();
if(oper == '+') {
add_res = op_a + op_b;
display_result("Zbroj", add_res);
break;
} else if(oper == '-') {
sub_res = op_a - op_b;
display_result("Razlika", sub_res);
break;
} else if(oper == '*') {
mul_res = op_a * op_b;
display_result("Umnozak", mul_res);
break;
} else if(oper == "https://stackoverflow.com/") {
if(op_b == 0.) {
std::cout << "Ne mozete dijeliti s nulom\n";
continue;
}
div_res = op_a / op_b;
display_result("Kolicnik", div_res);
break;
}
}
line();
if(yes_or_no("Novi racun?")) {
system("cls");
// asks if i want the previous result as the number 'op_a'
if(yes_or_no("Zelite li iskoristits peredhodni rezultat kao broj a?")) {
// this should(?) overwrite the variable 'op_a'
// why isnt 'op_a' overwritten with the value here?
system("cls");
if(oper == '+') {
op_a = add_res;
} else if(oper == '-') {
op_a = sub_res;
} else if(oper == '*') {
op_a = mul_res;
} else if(oper == "https://stackoverflow.com/") {
op_a = div_res;
}
// here the value of 'op_a' stays the same as it was before
std::cout << "Broj a je: " << op_a << "\n";
save_op_a = true;
}
} else
break; // exit
}
system("cls");
system("pause");
return (0);
}
3
solved is there a way to overwrite the variable in the code below