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
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;
}
+ 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.
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.
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.
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.