实验5
习题6-17:
源代码:
#include<iostream>
using namespace std;
int main() {
int p1;
int *p = &p1;
*p = 9;
cout << "The value at p:" << *p << endl;
system("pause");
return 0;
}
运行结果截图:
习题6-18:
源代码:
#include<iostream>
using namespace std;
int p1;
int *p = &p1;
int fnl() {
p = new int(5);
return *p;
}
int main() {
int a = fnl();
cout << "the value of a is: " << a << endl;
delete p;
system("pause");
return 0;
}
第3题不会
期中考试:
第一题:
源代码:
#include<cstdlib>
using namespace std;
class Dice{
public:
Dice (int n);
int cast();
private:
int sides;
};
Dice::Dice(int n):sides(n) {}
int a=rand()%sides+1;
return a;
}
int main(){
Dice p(40);
int m;
for(int i=0;i<500;i++)
{
m=p.cast();
if(m==27)
m++;
}
float n=m/500.0;
cout<<n<<endl;
return 0;
}
![](https://images2018.cnblogs.com/blog/1351884/201805/1351884-20180523212037307-1781771385.png)
第二题:
源代码:
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
class Dice {
private:int sides;
public:
Dice(int n) {
sides = n;
}
int cast() {
int m;
m = (rand() % (sides - 1 + 1) + 1);
return m;
}
};
int main() {
srand((unsigned)time(NULL));//切记:srand别放在循环体里,否则效果感人……
int n,x; cout << "请输入班级人数和你的学号:";
cin >> n >> x;
Dice A(n);
int i; int m;double y = 0.00;
for (i = 0; i < 500; i++) {
if (A.cast() == x)y++;
}
double p = (double)y / 500.00;
cout << "你的学号被抽中的概率为:" << p << endl;
return 0;
}
运行结果:
第三题不会...