0

Hi everybody,
I have a crazy problem with a basic calculator.

#include <iostream>
using namespace std;
main (){
     int num;
     int y;
     int ans;
     cin >> num;
     for (int x = 0;x < num;++x){
     cin >> y;
     ans += y;
     cout << ans << endl;
     }
     }

it take the quantity from the user and then adds this quantity of numbers and each time prints the answer, but when i add the first number, i get an error by 54, why???????????
Sorry if im not clear and thanks.

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by Karlwakim
0

The variable ans is initialized but not set.

Right before your for() loop you should write ans = num; otherwise ans will just have a garbage value in it.


EDIT

Or you can change line 7 from cin >> num; to cin >> ans; .

Edited by sfuo: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.