从循环内部访问最后一次迭代的值

Accessing the value of the last iteration from inside the loop

我知道这可能只是一个我不知道放在哪里的 if 语句,但我很难理解如何继续。


#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;
}

输出:

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

股息应该是一个变量 (tA)/所有 5 个随机生成的数字 (2.674) 的总和,'a' 的每个随机值在每一行(在 bin 列内)乘以它。但我不知道如何访问它,因为在代码中它是 'sum'

的最后一次迭代

如您所见,我的下一步是将所有五个值放入指定数组 bin *int b[5](标记为 5、10、15、30、100)。并最终将每个 bin 中的预期频率与 bin 标签(5,10,15.. 1000)相乘不胜感激。

您只能在循环结束后计算 divident,但您想从第一次迭代开始使用它:使用单个循环是不可能的。您应该使用两个循环,第一个循环计算 sumdivident,第二个循环显示值:

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;
}