#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() 删除临时文件返回没有错误代码 main 函数应该初始化一个 HISTOGRAM 数据数组并使用 C' 执行掷骰子的模拟