Check bellow to see how i solved this silly big problem.
I am currently trying to learn how to preform any mathematical operation (in the console) to the result of the previous mathematical operation, for example:
user inputs 1
+
2
system("cls");
3
*
2
system("cls");
6
/
2
system("cls");
3
so on and so forth.
Here is my code:
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
int main()
{
double num,num2, res;
string fchoice;
char choice;
system("cls");
cout << "0\b";
cin >> num;
system("cls");
cout << num << "\n\n";
cout << num << endl;
LOOP:
cin >> choice;
cout << "\n";
switch(choice)
{
case '+' :
cin >> num2;
res = num + num2 ;
system("cls");
cout << res << endl;
break;
case '-' :
cin >> num2;
res = num - num2 ;
system("cls");
cout << res << endl;
break;
case '/' :
cin >> num2;
res = num / num2 ;
system("cls");
cout << res << endl;
break;
case '*' :
cin >> num2;
res = num * num2 ;
system("cls");
cout << res << endl;
break;
}
return 0;
}
But the problem is, i don't know how to store the last result. So my questions are (if it's not too much trouble for you guys):
How to make the console reset (or delete) the previous results if the user enters a number and not an operation, and make the console ready to make new operations?
If you guys could give me some hints, i'll thankful.
EDIT: I forgot to mention that am a beginner.
All i had to do was simply add this line to rewrite the previously defined double num
to num = res;
just before the goto LOOP;
so it would always return to the beginning.
You really should stop using goto statements and start using loops for this. (BTW I can see your label, but not your goto statement? ). To answer your second question, you could add a default statement in the switch statement, which will make it go back to the top if not an
default:
goto (any label at beginning of program);
Or if you were using a while loop, just clear all your values in the default statement.
As a footnote, why write the
cout<<res<<endl;
4 times? just write outside the switch once.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.