Why isn't my c++ 'calculator' working? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why isn't my c++ 'calculator' working?

The point of this program was to get user input five times, adding each number to the 'total'. However, when I put in very small numbers 1 as input, I get a string of "Your total is 2686821" over and over again, followed by the phrase Time limit exceeded. Here is my program: #include <iostream> using namespace std; int main() { int num, number, total; num = 1; while(num <= 5) { cin >> number; total += number; num++; } while(num = 5) { cout << "Your total is" << total << endl; } return 0; } EDIT: Thank you all for the advice, it works perfectly now :D

26th Jun 2017, 4:13 PM
Somebody that you used to know
Somebody that you used to know - avatar
5 Answers
+ 5
One of the reasons is because user input doesn't work well with loops on Code Playground. Apart from that, variable total is uninitialised, and hence may store garbage values. Another thing (which prolly is a typo) is the operator to check for value equality, == instead of = in your second while loop. You might also want to change your second while loop to an if statement, or just remove the second loop directly. #include <iostream> using namespace std; int main() { int num, number, total; num = total = 0; while(num < 5) { cin >> number; total += number; num++; } cout << "Your total is" << total << endl; return 0; }
26th Jun 2017, 3:18 PM
Hatsy Rei
Hatsy Rei - avatar
+ 2
total should be declared before using it. add this line to your code. total = 0; and also as mentioned in above you should use == to check the equality.
26th Jun 2017, 3:28 PM
NSA94
NSA94 - avatar
0
Correct this point while(num=5){ pr....... } just after the first loop follow it with the the print statement remember that when in looping the program will loop until the condition is false this means when num==5 it will automatically move to the next statement. also note that num=5 is not the same as num==5 they are assignment and conditional operators respectively.
26th Jun 2017, 3:22 PM
Nura Programmer
Nura Programmer - avatar
0
But its best to use this instead: int total = 0; for(int i=0; i<=5; ++i){ total += i; } cout<<"total is: "<<total<<endl; .....as this code is much better and did the same thing.
26th Jun 2017, 3:27 PM
Nura Programmer
Nura Programmer - avatar
0
Nuwan... remember that even if he uses the conditional operator he won't get the answer,, by the way the program will crashes since it is on looping this makes it loops for ever until runtime error acquire.
26th Jun 2017, 3:52 PM
Nura Programmer
Nura Programmer - avatar