Please help resolve time limit exceeded error. The question:
Write a program that works as a simple calculator.
1.It reads a character (ch)
2.If ch is among β+β, β-β, β*β, β/β or β%β it furthur takes two numbers (N1 and N2 as input). It then performs appropriate appropriate operation between numbers and print the number.
3.If ch is βXβ or βxβ, the program terminates.
4.If ch is any other character, the program should print βInvalid operation. Try again.β and seek inputs again (starting from character).
My code:
TLE Error in Basic Calculator
Still shows TLE
#include
using namespace std;
int main()
{
char ch;
int a, b;
cin >> ch;
if ((a >= 0 && a <= 100000000) && (b >= 0 && b <= 100000000))
{
while (ch != βXβ && ch != βxβ)
{
cin >> a >> b;
if (ch == β+β)
cout << a + b << endl;
else if (ch == β-β)
cout << a - b << endl;
else if (ch == β*β)
cout << a * b << endl;
else if (ch == β/β && b != 0)
cout << a / b << endl;
else if (ch == β%β && b != 0)
cout << a % b << endl;
else
cout << βInvalid operation. Try again.β << endl;
cin >> ch;
}
}
return 0;
}
@atmika2001_f655a0d2e84c0123 You have not changed the code according to what i told earlier. Take input of a and b ONLY if you get a valid operator
As per my understanding, we have to print output as βInvalid operation. Try again.β so, will need to take input in all cases (point 4 in question). Please let me know if Iβm missing something.
My code: https://ide.codingblocks.com/s/609394
Ques:
Write a program that works as a simple calculator.
1.It reads a character (ch)
2.If ch is among β+β, β-β, β*β, β/β or β%β it furthur takes two numbers (N1 and N2 as input). It then performs appropriate appropriate operation between numbers and print the number.
3.If ch is βXβ or βxβ, the program terminates.
4.If ch is any other character, the program should print βInvalid operation. Try again.β and seek inputs again (starting from character).
@Ishitagambhir
@atmika2001_f655a0d2e84c0123 see the sample input that is given, when ; is given then you dont have to take input for a and b you have to take input for operator again.
So take input for a and b inside the if conditions only when the operator is valid
It is working now, thanks!
I hope Iβve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.