bahrenze1
bahrenze1

Reputation: 3

Accessing the value of the last iteration from inside the loop

I know this might be just an if statement that i don't know where to place but i am having difficulties understanding how to proceed.


#include <time.h>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    float a;
    float sum;
    float tA = 5050 ;
    int b [5] = {5, 10, 15, 30, 100};
    double bin;
    double divident;
    cout<<"Random numbers generated between 0 and 1:"<<endl;
    srand( (unsigned)time( NULL ) );
    
    for (int i = 0; i < 5; i++) 
    {
        a = (float) rand()/RAND_MAX; 
        sum += a;
        cout << a << "\t Total: " << sum << "\t Bin: " << a* divident << endl;
    }
        cout << "Total of Random Numbers: " << sum << endl;
        divident = tA/sum;
        cout <<"Divident: "<< divident << endl;
        cout <<"Last a: "<< a << endl;
        
    return 0;
}

OUTPUT:

Random numbers generated between 0 and 1:
0.228659         Total: 0.228659         Bin: 0
0.337218         Total: 0.565877         Bin: 0
0.955376         Total: 1.52125          Bin: 0
0.356451         Total: 1.8777           Bin: 0
0.7963           Total: 2.674            Bin: 0
Total of Random Numbers: 2.674
Divident: 1888.55
Last a: 0.7963

The dividend should be a variable (tA)/the sum of all 5 random generated numbers (2.674) and every random value of 'a' be multiplied by it on every row (inside bin column). But I do not know exactly how to access it since in the code it is the last iteration of 'sum'

as you can see my next step is to place all five values into a designated array bin *int b[5](labeled 5, 10, 15, 30, 100). and eventually multiply the expected frequency in every bin with the bin label(5,10,15.. 1000) I'm thinking std map or something similar, so any advanced std solutions or pointers (sic) on how to proceed further would greatly be appreciated.

Upvotes: 0

Views: 95

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 149145

You can only compute divident after the end of the loop, but you want to use it starting with the first iteration: that is not possible using one single loop. You should use two loops, first one to compute sum and divident, and second one to display the values:

float sum = 0;
...
double arr[5];
for (int i = 0; i < 5; i++)
{
    a = (float)rand() / RAND_MAX;
    sum += a;
    arr[i] = a;
}
divident = tA / sum;
for (int i = 0; i < 5; i++)
{
    a = arr[i];
    cout << a << "\t Total: " << sum << "\t Bin: " << a * divident << endl;
}

Upvotes: 0

Related Questions