这是一种在 c++ 之外使用随机数形式的解决方法。
这是 C 语言的原始程序,从“http://www.programmingsimplified.com/”复制而来
该程序无法运行,因为“temp1 = 1 + random (588);”
“temp2 = 1 + 随机(380);”
语句不起作用。 “随机”不是 graphics.h、conio.h 或 stdlib.h 的函数
如果包含 random.h,它也不起作用。
此清单下方是随机函数的解决方法。
#include<graphics.h>
#include<conio.h>
#include<stdlib.h>
main()
{
int gd = DETECT, gm, area, temp1, temp2, left = 25, top = 75;
void *p;
initgraph(&gd,&gm,"C:\\TC\\BGI");
setcolor(YELLOW);
circle(50,100,25);
setfillstyle(SOLID_FILL,YELLOW);
floodfill(50,100,YELLOW);
setcolor(BLACK);
setfillstyle(SOLID_FILL,BLACK);
fillellipse(44,85,2,6);
fillellipse(56,85,2,6);
ellipse(50,100,205,335,20,9);
ellipse(50,100,205,335,20,10);
ellipse(50,100,205,335,20,11);
area = imagesize(left, top, left + 50, top + 50);
p = malloc(area);
setcolor(WHITE);
settextstyle(SANS_SERIF_FONT,HORIZ_DIR,2);
outtextxy(155,451,"Smiling Face Animation");
setcolor(BLUE);
rectangle(0,0,639,449);
while(!kbhit())
{
temp1 = 1 + random ( 588 );
temp2 = 1 + random ( 380 );
getimage(left, top, left + 50, top + 50, p);
putimage(left, top, p, XOR_PUT);
putimage(temp1 , temp2, p, XOR_PUT);
delay(100);
left = temp1;
top = temp2;
}
getch();
closegraph();
return 0;
}
随机数是用一个简单的 MS Excel 宏生成的,这里列出:
Sub Macro1()
Dim i
For i = 1 To 400
Randomize
Range("a" & i) = Int(Rnd * 588) + 1
Range("b" & i) = Int(Rnd * 380) + 1
Next i
End Sub
这会生成 2 列随机数。每一列都被复制并粘贴到
它自己的 *.txt 文件,即 rnd1.txt 和 rnd2.txt 并放置在可以放置它们的目录中
由后面的 c++ 程序访问。
用正确的路径替换“c:\PATH\rnd1.txt”和“C:\PATH\rnd2.txt”。
#include<iostream>
#include<fstream>
#include<graphics.h>
using namespace std;
int i,j,k;
int main(int argc, char** argv) {
std::ifstream infile1;
infile1.open("c:\\PATH\\rnd1.txt",ios::in);
ifstream infile2;
infile2.open("c:\\PATH\\rnd2.txt",ios::in);
int gd = DETECT, gm, area, temp1, temp2, left = 25, top = 75;
void *p;
initgraph(&gd,&gm,"C:\\TC\\BGI");
setcolor(YELLOW);
circle(50,100,25);
setfillstyle(SOLID_FILL,YELLOW);
floodfill(50,100,YELLOW);
setcolor(BLACK);
setfillstyle(SOLID_FILL,BLACK);
fillellipse(44,85,2,6);
fillellipse(56,85,2,6);
ellipse(50,100,205,335,20,9);
ellipse(50,100,205,335,20,10);
ellipse(50,100,205,335,20,11);
area = imagesize(left, top, left + 50, top + 50);
p = malloc(area);
setcolor(WHITE);
settextstyle(SANS_SERIF_FONT,HORIZ_DIR,2);
outtextxy(155,451,"Smiling Face Animation ");
setcolor(BLUE);
rectangle(0,0,639,449);
while(!kbhit())
{
infile1 >> j;
temp1 = j;
infile2 >> k;
temp2 = k;
if(infile2.eof()) {
closegraph();
void close();
return 0;
}
getimage(left, top, left + 50, top + 50, p);
putimage(left, top, p, XOR_PUT);
putimage(temp1 , temp2, p, XOR_PUT);
delay(100);
left = temp1;
top = temp2;
}
}
此程序将运行大约 40 秒,然后终止。