#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <math.h>
void plotResults(double* xData, double* yData, int dataSize);
int main()
{
int i = 0;
int d1, d2, d3;
int a[16];
srand(time(NULL));
for(i = 0; i <= 15; i++)
a[i] = 0;
for(i = 0; i < 100; i = i + 1)
{
d1 = rand() % 6 + 1; //randomized dice rolls
d2 = rand() % 6 + 1;
d3 = rand() % 6 + 1;
++a[d1 + d2 + d3 - 3];
}
char asterisks[0x400];
memset(asterisks, '*', sizeof(asterisks)); //copies the character value to the # of bytes to be set to the value
int nIntervals = 0;
double* xData = (double*) malloc((nIntervals+1)*sizeof(double));
double* yData = (double*) malloc((nIntervals+1)*sizeof(double));
xData[0] = 0.0;
double x0 = 0.0;
for (i = 0; i < 18; i++) {
x0 = xData[i];
xData[i+1] = x0 + 1;
}
for (i = 0; i <= nIntervals; i++) {
x0 = xData[i];
yData[i] = a[i];
}
plotResults(xData,yData,nIntervals);
return 0;
}
void plotResults(double* xData, double* yData, int dataSize) {
FILE *gnuplotPipe,*tempDataFile;
char *tempDataFileName;
double x,y;
int i;
tempDataFileName = "tempData";
gnuplotPipe = popen("/usr/bin/X11/gnuplot -persist","w");
if (gnuplotPipe) {
fprintf(gnuplotPipe,"plot \"%s\" with lines\n",tempDataFileName);
fflush(gnuplotPipe);
tempDataFile = fopen(tempDataFileName,"w");
for (i=0; i <= dataSize; i++) {
x = xData[i];
y = yData[i];
fprintf(tempDataFile,"%lf %lf\n",x,y);
}
fclose(tempDataFile);
printf("press enter to continue...");
getchar();
remove(tempDataFileName);
fprintf(gnuplotPipe,"exit \n");
} else {
printf("gnuplot not found...");
}
我需要让这个程序工作,采用骰子滚动算法,并打印出图形的直方图。
方向:该程序应重复使用之前实验室中生成的代码来模拟滚动三个骰子的结果并获取各个结果的总和。直方图应由您的C程序驱动的gnuplot程序包生成。您应该编写一个函数来处理管道,将指向直方图数据(HISTOGRAM)数组的指针和数组大小作为输入。然后应执行以下步骤: 打开管道到gnuplot 如果管道存在,则发送命令 冲洗管道 打开临时文件来存储直方图数据 在临时文件上写直方图数据 关闭临时文件 使用getchar()暂停程序 删除临时文件 返回没有错误代码 主函数应该初始化一个HISTOGRAM数据数组,并使用C函数srand和rand执行掷骰子模拟。