Hello. I tried to do this simple "calculator" but it doesn't work the way I want. It gets result right but the first three numbers from the array are weird. Why does it happen?
#include<iostream>
usingnamespace std;
int main()
{
double res = 0; // <==== Avoid unnecessary global variables; also: INITIALISE
int q;
cout << "How many numbers? ";
cin >> q;
double *in = newdouble[q]; // <==== Whatever container you use, only declare this ONCE
for ( int pos = 0; pos < q; pos++ ) // <==== Arrays count from 0: you'll have to deal with it
{
cout << "Enter " << pos + 1 << ". number: ";
cin >> in[pos];
res += in[pos];
}
cout << endl;
for ( int pos = 0; pos < q; pos++ ) // <==== Limits as above
{
cout << in[pos];
if ( pos < q - 1 ) cout << " + ";
}
cout << " = " << res << endl;
delete [] in; // <==== If using dynamic arrays
}
How many numbers? 10
Enter 1. number: 2
Enter 2. number: 5
Enter 3. number: 3
Enter 4. number: 7
Enter 5. number: 9
Enter 6. number: 11
Enter 7. number: 14
Enter 8. number: 1
Enter 9. number: 19
Enter 10. number: 23
2 + 5 + 3 + 7 + 9 + 11 + 14 + 1 + 19 + 23 = 94
I will probably be expelled by the forum if I don't mention that you can avoid the dynamic arrays (use of new and delete above) if you use vector<double> in( q );
instead of the dynamically-allocated array in the code above. Access to its elements via [] looks exactly the same. If you use this then (i) add a header #include<vector> and (ii) remove the delete [] in; line.