PDA

Click to See Complete Forum and Search --> : compiles, but doesn't run correctly, problem w/ for loop or if condition


struntz
Jan 19th, 2002, 03:42 PM
Hello everyone! :D

i've been trying to figure this code otu for awhile and i don't know why this isnt' working maybe the problem isn't even with the if condition, but here is the code:


#include <iostream>
#include <iomanip>
using namespace std;


int main()
{
const int NUM = 3; //for debugging, should be larger #
double amount, total = 0, *data;
int count = 0, size = NUM;
data = new double[size]; //initial array on the heap

do
{
cout <<" Enter amount (or 0 to finish): ";
cin >> amount;
if(amount == 0) break;

if(count == size)
{
double *q = new double[2*size];
cout <<"More memory alocated: size = " << size << endl;
for(int i = 0; i < size; i++)
{
q[i] = data[i];
size *= 2;
delete [] data;
data = q;
}
total += amount;
data[count++] = amount;
}

}while(true);
//get next inputed value
if(amount != 0)
{
cout <<"Out of memory: input was terminated\n";
cout <<"The value " << amount << " is not saved" << endl;
}
cout <<"\n Total of" << count << "values is"
<< total << endl;
if(count == 0) return 0;
cout << "\n Tran no. Amount\n\n";
cout.setf(ios::fixed);
cout.precision(2);
for(int i =0; i < count; i++)
{
cout << setw(4); cout << i+1;
cout << setw(11); cout << data[i] << endl;
}
return 0;
}

when i compile this, it compiles fine, but when i run this, after i enter more than 3 values, it should break off into this condition


if(count == size)
{
double *q = new double[2*size];
cout <<"More memory alocated: size = " << size << endl;
for(int i = 0; i < size; i++)
{
q[i] = data[i];
size *= 2;
delete [] data;
data = q;
}


but it will let me enter mutliply numbers, i can add as much as i want and when i type in 0, it breaks and prints out
total number of 0 values is 0

the problem maybe in the for loop.....

thanksf or listening :D

ravcam
Jan 19th, 2002, 10:15 PM
Yes... it is a problem with your loop...

if(count == size)

this is incorrect.... because prior to this line the count = 0 and size equals 3... I can find out no other point in your program where you update count... so that loop will never execute or update any values.

CornedBee
Jan 21st, 2002, 05:38 PM
I think count and amount should be the same variable...

You should call delete[] on the dynamic array (actually I don't see why you make it dynamic).