循环循环并执行while循环

时间:2017-11-08 22:15:49

标签: c

我的程序应该运行随机数并将它们存储到数组中。一旦压力达到100 Psi正跳跃的点,do-while循环应该停止并记录事件0之前的10个数字和之后的10个数字,然后打印它们。但是,do-while循环结束但是事件-1和0很少有+100 psi的跳跃。任何帮助表示赞赏!

#include <stdio.h>
#include <stdlib.h>
#include <math.h> 
#include <time.h>

typedef struct
{
    int t; //time.
    int tp, tt, tf; //value pressure, Na temperature, and Na flow.
} Data_slice;

void get_value(int*, int*, int*);
void printit(Data_slice data[], int);
void printitx(Data_slice data[], int);

int main()
{
    srand(time(NULL));
    int randNumP, randNumT, randNumF, n = 0, old, k, x = 0, z;
    Data_slice data[21];
    do
    {
        k = n % 21;
        get_value(&randNumP, &randNumT, &randNumF);
        data[k].t = k;
        data[k].tp = randNumP;
        data[k].tt = randNumT;
        data[k].tf = randNumF;
        old = data[k - 1].tp; //checking value before.
        n++;
    } while ((randNumP - old) < 100);
    z = k + 1;
    for (x = 0; x < 10; x++)
    {
        get_value(&randNumP, &randNumT, &randNumF);
        data[z].t = z;
        data[z].tp = randNumP;
        data[z].tt = randNumT;
        data[z].tf = randNumF;
        n++;
    }
    printf("Time\t\tPressure\tFlow\tTemperature\n");
    printitx(data, k);
    printit(data, z);

    return 0;
}

void get_value(int * randNumP, int * randNumT, int * randNumF)
{
    *randNumP = rand() % 201 + 500;
    *randNumT = rand() % 101 + 100;
    *randNumF = rand() % 11 + 10;
}

void printit(Data_slice data[], int z)
{
    int j;
    for (j = 0; j < 11; j++)
    {
        printf("%d\t\t%d\t\t%d\t\t%d\n", j, data[z].tp, data[z].tf, data[z].tt);
        z++;
    }
}

void printitx(Data_slice data[], int k)
{
    int w;
    for (w = -10; w < 0; w++)
    {
        printf("%d\t\t%d\t\t%d\t\t%d\n", w, data[k].tp, data[k].tf, data[k].tt);
        k++;
    }
}

1 个答案:

答案 0 :(得分:0)

如评论中所述,您在第一次迭代时访问数据[-1],这很糟糕。一种解决方法是在第一次迭代时使用randNumP + 100设置old值。像这样:

old = (n==0) ? randNumP +100 : data[k-1].tp;