程序设计复习3
看了网上的一个课程,讲的是金山打字游戏,自己写代码尝试了一下,实现了一些功能。其中碰到了一些比较有趣的问题
关于随机数rand()和srand()
单独使用rand()会默认添加一个srand()函数
在C++中,当srand中的参数相同(即随机数种子相同)时,则产生的伪随机数列也相同
srand函数用于为rand函数产生随机数种子
通常用time(NULL)作为srand函数的传入参数;
当使用time(NULL)作为srand函数的传入参数时,rand函数则以时间作为随机数种子进而产生随机数
代码一
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
srand(time(NULL));
for (int i = 0; i < 100; i++) {
cout << rand() % 100 << endl;
}
return 0;
}
代码二
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
for (int i = 0; i < 100; i++) {
srand(time(NULL));
cout << rand() % 100 << endl;
}
return 0;
}
代码一会产生100个不相同的随机数,而代码二会产生100个相同的随机数。
主要原因是用时间作为种子,而for循环时间较短,产生的种子几乎相同,导致随机数相同
网上说的这个 没怎么看懂,先留在这里吧
C风格的强制类型转换
转换的含义是通过改变一个变量的类型为别的类型从而改变该变量的表示方式。为了类型转换一个简单对象为另一个对象你会使用传统的类型转换操作符。比如,为了转换一个类型为doubole的浮点数的指针到整型:
代码:
int i;
double d;
i = (int) d;或者:i = int (d);
对于具有标准定义转换的简单类型而言工作的很好。然而,这样的转换符也能不分皂白的应用于类(class)和类的指针。ANSI-C++标准定义了四个新的转换符:’reinterpret_cast’, ‘static_cast’, ‘dynamic_cast’ 和 ‘const_cast’,目的在于控制类(class)之间的类型转换。
代码:
•reinterpret_cast(expression)
•dynamic_cast(expression)
•static_cast(expression)
•const_cast(expression)
1 reinterpret_cast
reinterpret_cast 转换一个指针为其它类型的指针。它也允许从一个指针转换为整数类型。反之亦然。
这个操作符能够在非相关的类型之间转换。操作结果只是简单的从一个指针到别的指针的值的二进制拷贝。在类型之间指向的内容不做任何类型的检查和转换。如果情况是从一个指针到整型的拷贝,内容的解释是系统相关的,所以任何的实现都不是方便的。一个转换到足够大的整型能够包含它的指针是能够转换回有效的指针的。
代码:
class A {};
class B {};
A * a = new A;
B * b = reinterpret_cast
#include <iostream>
#include "stdlib.h"
#include "time.h"
#include "conio.h"
#include "windows.h"
using namespace std;
void enlline(int num)
{
for (int i = 0; i < num; i++)
{
cout << endl;
}
}
void cspace(int num)
{
for (int i = 0; i < num; i++)
{
cout << " ";
}
}
void gamestart()
{
enlline(14);
cspace(48);
cout << "put any key to start" << endl;
_getch();
system("cls");
}
void headline(int &x,int &y)
{
cspace(20);
cout << "Pass " << x;
cspace(20);
cout << "Score " << y;
cout << endl;
for (int i = 0; i < 80; i++)
cout << '-';
cout << endl;
}
void game(int &pass, int &score)
{
int line = 1;
int sline = 0;
srand(time(0));
int x = rand() % 26;
int y = rand() % 80;
while (true)
{
char a =char(65 + x);
cspace(y);
cout <<a ;
Sleep(500-pass*20);
cout << "\b";
sline += line;
if (sline > 23)
{
score -= 10;
break;
}
enlline(line++);
if (_kbhit())
{
char b = _getch();
if (b==a)
{
score += 10;
break;
}
else
{
score -= 10;
break;
}
}
if(score>0)
pass = score / 30;
}
}
int main()
{
int pass=0, score = 0;
gamestart();
while (score > -50)
{
headline(pass, score);
game(pass, score);
system("cls");
}
enlline(14);
cspace(48);
cout << "game over";
getchar();
return 0;
}
vs2017用的还不是太熟,调试单个源文件,运行结束时不退出等一系列问题有待解决