-2
int main()
{
    int n, inInt;
    vector <int> list;
    ifstream ifs("1.txt");
    float a;
    ifs >> a;
    std::vector<int> result;
    int temp;

    while(! ifs.eof())
    {
        ifs >> temp;
        result.push_back(temp);
    }

    int b;
    b = result.size();
    float array[b+1];
    int i;
    array[0] = a;

    for(i = 1;i < b+1;i++) {
        array[i] = (array[i-1] + result[i]-2*array[i-1] * result[i]/a); 
    }
    cout << array[b];

    system("pause");
    return 0;}

Basically in my code, I built a vector and build an array and try to use the data from the vector in the array.However,when I text the code,it gave me a huge incorrect number.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
  • 3
    Please don't edit your question to make existing answers wrong. If the answers solve the initial problem but you then encounter a new problem that you can't solve please post a new question. – ChrisF Jul 25 '13 at 22:51

2 Answers2

2

temp is not an array, temp is an int. You're trying to use operator[] on an int you cannot do that. Also, VLAs (Variable Length Arrays) are a GCC extension, and therefore not standard. I suggest you replace this line:

float array[b+1];

With:

std::vector<float> array(b+1);
Borgleader
  • 15,826
  • 5
  • 46
  • 62
  • sorry I am not quite familiar with vector.Then array[i] = (array[i-1] + result[i]-2*array[i-1] * result[i]/a); how can i edit this part? – user2604063 Jul 21 '13 at 13:55
  • You don't need to. Vectors act just like array, the difference is they can change in size and manage their own memory (amongst other things). Operator [] works on vectors just like it does on arrays. – Borgleader Jul 21 '13 at 13:56
  • std::vector array(b+1)...?is this an array or a vector...? – user2604063 Jul 21 '13 at 13:57
  • `std::vector array(b+1);` is a variable of name array, of type vector (that holds floats) which contains b+1 elements. – Borgleader Jul 21 '13 at 13:58
  • The input is 3 2 2 ,suppose to get 1.66666667,but evertime still get a random huge number. – user2604063 Jul 21 '13 at 14:01
0

I see at least two problems. First, your input loop is incorrect and inserts an invalid entry into result. You can fix this by using the following input loop:

while (ifs >> temp)
{
    result.push_back(temp);
}

Second, the vector result contains b elements so the valid indices are [0..b-1]. Your loop end condition i < b+1 will read one element past the end of result. I think you can fix this issue by doing this instead:

for(i = 0; i < b; i++)
{
    array[i+1] = (array[i] + result[i]-2*array[i] * result[i]/a);
}

When I made these changes and used 3 2 2 for input, the output was 1.66667

Community
  • 1
  • 1
Blastfurnace
  • 18,411
  • 56
  • 55
  • 70